您的位置:首页 > 其它

LeetCode------Two Sum

2018-01-26 17:02 417 查看
1. Description: Given an array of integers, return indices of the two numbers such that they add up to a specified target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

2. 翻译:给定一个整数数组和一个目标值,返回数组中两个元素的下标,并使这两个元素之和等于该目标值。可以假设每个目标值对应的两个下标值的解是唯一的,并且数组中的同一个元素不能够使用两次。

 比如说数组nums = [2,7,11,15],目标值target = 9, 因为2 + 7 = 9,所以返回[0,1]。

3.思路:这道题目比较简单,属于easy难度。我们可以直接通过两层for循环进行遍历的方式,依次检查两个元素之和是否等于目标值,一旦发现符合条件的两个数组元素,立即返回这两个下标值所组成的数组,如果遍历结束后仍没有发现这样的两个元素,则返回null,代码如下。Submit Solution结果为Accepted。

4.代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
//首先数组长度必须大于等于两个元素
if(nums.length>1){
for(int i = 0; i<nums.length; i++){
for(int j = i+1; j<nums.length; j++){
if((nums[i]+nums[j]) == target){
return new int[]{i,j};
}
else{
//do nothing
}
}
}
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: