Leecode-TwoSum-Hashmap法和双指针法-Java

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

两种思路:

  1. 用hashmap存一下,key为数值,value也是数值。遍历数组,判断一下map的key中是否含有target-nums[i],有的话可以返回。 返回的时候可以返回下标,也可以返回是那两个值。
  2. 双指针法。首先需要对数组进行升序排序(排序了,就注定不能返回下标,只能返回那两个值),一个下标指向末尾,一个指向开头。如果开头和末尾两元素之和大于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]);


    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值