问题描述:
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, and you may not use the same element twice.
即给定一个整型数组,返回两个数的索引使得它们相加等于给定标志数字。
举例:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int i = 0; i <= nums.length - 1; i++) {
for (int j = 0; j <= nums.length - 1; j++) {
if (nums[i] + nums[j] == target && i != j) {
return new int[]{i,j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}