leetcode之Two Sum
【摘要】 The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 ...
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
中文理解:给你一个数组,和一个目标值,数组里面任意2个元素的值之和等于目标值,然后返回这2个元素的下标,下标从一开始,不是0开始,上面的结果index1=1,index2=2就知道了
-
public class Solution {
-
public int[] twoSum(int[] nums, int target) {
-
int index1=0;
-
int index2=1;
-
for(int i=0;i<nums.length;i++){
-
for(int j=i+1;j<nums.length;j++){
-
if(nums[i]+nums[j]==target){
-
index1=i+1;
-
index2=j+1;
-
}
-
}
-
}
-
int[] a=new int[2];
-
a[0]=index1;
-
a[1]=index2;
-
return a;
-
}
-
}
文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。
原文链接:chenyu.blog.csdn.net/article/details/49493759
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)