两数只和(twoSum)
点击链接加入群聊【java菜鸟学习】:https://jq.qq.com/?_wv=1027&k=5afU7nS
群号:124569404
- 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。
- 您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素。
由于需要考虑负数以及两个数字相同的情况,暂未想到很好的解决办法(Map不能存储相同的数字)
/**
* ClassName: Twosum
*
* @author leegoo
* @Description:
* @date 2019年01月09日
*/
public class Twosum {
/**
* Given an array of integers, return indices of the two numbers such that they add up to a specific target.
* <p>
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
* Example:
* <p>
* Given nums = [2, 7, 11, 15], target = 9,
* <p>
* Because nums[0] + nums[1] = 2 + 7 = 9,
* return [0, 1].
*
* @param args
*/
public static void main(String[] args) {
int[] nums = new int[]{3,2,4};
int target = 6;
int[] ints = twoSum(target, nums);
}
public static int[] twoSum(int target, int[] nums) {
int[] res = new int[]{0, 0};
outloop:
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (i != j && nums[i] + nums[j] == target) {
res[0] = i;
res[1] = j;
break outloop;
}
}
}
return res;
}
}