求两数的和
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目很简单,思路也很直接,直接设定当前的数是符合条件的其中一个,那么找到剩下那个符合条件的下标就可以了:
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
boolean flag = true;
for (int i = 0; i < nums.length && flag; i++){
int temp = target - nums[i];
int idx = i + 1;
while (idx < nums.length){
if (nums[idx] == temp){
res[0] = i;
res[1] = idx;
flag = false;
break;
}else {
idx++;
}
}
}
return res;
}
执行结果也算OK,分享一下^^

浙公网安备 33010602011771号