public int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
for(int i=0;iint add2=target-nums[i];
for(int j=i+1;jif(nums[j]==add2)
{
result[0]=i;
result[1]=j;
return result;
}
}
}
return result;
}
方法二:可以借助HashMap,将nums加入到HashMap表中,其中nums中的数作为key,索引作为value, 判断Hashmap中存在target-x且这个数的索引值不等于x自身即可。
代码
public int[] twoSum(int[] nums, int target) {
Map map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
public static List> threeSum(int[] nums) {
List> list = new ArrayList>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
if (nums[left] + nums[right] + nums[i] > 0) {
right--;
} else if (nums[left] + nums[right] + nums[i] < 0) {
left++;
} else {
list.add(Arrays.asList(nums[left], nums[right], nums[i]));
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
}
}
}
return list;
}
public static List> fourSum(int[] nums, int target) {
List> result = new ArrayList>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (left < right) {
if (nums[i] + nums[j] + nums[left] + nums[right] < target) {
left++;
} else if (nums[i] + nums[j] + nums[left] + nums[right] > target) {
right--;
} else {
result.add(Arrays.asList(nums[i], nums[j], nums[left],
nums[right]));
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
}
}
}
}
return result;
}