给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
两种思路:
- 用hashmap存一下,key为数值,value也是数值。遍历数组,判断一下map的key中是否含有target-nums[i],有的话可以返回。 返回的时候可以返回下标,也可以返回是那两个值。
- 双指针法。首先需要对数组进行升序排序(排序了,就注定不能返回下标,只能返回那两个值),一个下标指向末尾,一个指向开头。如果开头和末尾两元素之和大于target,那么末尾指针向左边移动,小于起始指针向右移动,等于则返回。
import java.util.Map;
import java.util.HashMap;
public class TwoSum {
public static int[] getTwoSum(int[] nums, int target){
if(nums.length == 0){
return null;
}
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int num = target - nums[i];
if(map.containsKey(num)){
//int[] res = new int[] {nums[i], num}; //这样是返回值
int[] res = new int[] {i, map.get(num)}; //返回下标 注意这里get里写的是num 不是nums[num]
return res;
}
map.put(nums[i], i); //后面这个i可以用来返回下标,在这里没有用到。
}
return null;
}
public static void quickSort(int[] nums, int begin, int end){
if(begin >= end){
return ;
}
int pivot = nums[begin];
int i = begin;
int j = end;
while(i < j){
while(nums[j] >= pivot && i < j){
j--;
}
while(nums[i] <= pivot && i < j){
i++;
}
if(i < j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
nums[begin] = nums[i];
nums[i] = pivot;
quickSort(nums, begin, i-1);
quickSort(nums, i+1, end);
}
public static int[] getTwoSum2(int[] nums, int target){
int i = 0;
int j = nums.length-1;
while(i < j){
if((nums[i] + nums[j]) == target){
return new int[]{nums[i], nums[j]};
}else if((nums[i] + nums[j]) > target){
j--;
}else{
i++;
}
}
return null;
}
public static void main(String[] args) {
int[] nums = {1,3,8,5,6};
int target = 9;
int[] res ;
res = getTwoSum(nums, target);
for (int i : nums) {
System.out.println(i);
}
//quickSort(nums, 0, nums.length-1);
// res = getTwoSum2(nums, target);
System.out.println(res[0] +" "+ res[1]);
}
}