LeetCode(62)-Two Sum
2016-04-15 16:58
453 查看
题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. UPDATE (2016/2/13): The return format had been changed to zero-based indices. Please read the above updated description carefully.
思路:
题意:给定一个互不相同的整数数组nums,给定一个目标值target,求两个索引值,相应的值的和等于target首先排除nums == null和nums.length < 2,返回null,至于其他的情况可以用两个循环解决
代码:
public class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; int n = nums.length; if(n < 2 || nums == null){ return null; } for(int i = 0;i < n;i++){ for(int j = i+1;j < n;j++){ if(nums[i] + nums[j] == target){ result[0] = i; result[1] = j; return result; } } } return null; } }
相关文章推荐
- 可视化理解卷积神经网络-ECCV 2014
- 使用SVN主干与分支功能
- 属性动画旋转示意图
- Android 源码5.1调用系统设置页面
- Installing node.js on ubuntu server 15.10
- 简单选择排序
- Android实用工具类-GrallyAndPhotoUtils图片处理工具
- Natural Merge Sort(自然归并排序)
- 课堂练习--第7周(两人结对)
- 实现Web虚拟现实的最轻松方案—A-Frame框架
- android 根据域名得到IP
- android 获取屏幕高度和宽度
- 移动前端开发之viewport的深入理解
- LeetCode 83 -Remove Duplicates from Sorted List ( JAVA )
- 透明UIView图设置
- Windows平台下GCC编程之反向输出整数
- ZOJ 1048
- 新人报道
- 高通QCOM 8610平台电量计算
- ABAP 日期时间函数