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].
Java
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] tempNums = new int[2];
for (int i = 0; i < nums.length; i++) {
int a = nums[i];
for (int j = nums.length - 1; j > i; j--) {
int b = nums[j];
if (a + b == target) {
tempNums[0] = i;
tempNums[1] = j;
}
}
}
return tempNums;
}
}
注意
双层for循环,一个从前向后,一个从后先前,并且避免重复。