LeetCode_1:两数之和

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

开始想了个很笨的方法:

  1. 先对数组进行一个排序
  2. 使用双指针,一个指向头less,一个指向尾more
  3. 两个指针位置上的数相加
  4. 如果小于target,那么less++
  5. 如果小于target,那么more–
  6. 如果相等,则找到了两个对应的值
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int num[] = new int[nums.length];
        for(int i = 0;i < nums.length;i++){
            num[i] = nums[i];
        }
        Arrays.sort(nums);
        int[] arr = new int[2];
        int less = 0;
        int more = nums.length - 1;
        while(less < more){
            if(nums[less] + nums[more] < target){
                less++;
            } else if(nums[less] + nums[more] > target){
                more--;
            } else {
                arr[0] = nums[less];
                arr[1] = nums[more];
                break;
            }
        }
        for(int i =0;i < num.length;i++){
            if(num[i] == arr[0]){
                arr[0] = i;
                break;
            }
        }
        for(int i = num.length - 1;i >= 0;i--){
            if(num[i] == arr[1]){
                arr[1] = i;
                break;
            }
        }
        return arr;
    }
}

然后看了下官方的解答,感觉自己好笨,太菜了

  1. 使用HashMap,值作为key,对应的下标作为value
  2. 遍历扫描数组,将数组的值存入Map当中
  3. 用target减去数组上的数,得出一个差值
  4. 检查这个差值是否存在于HashMap当中
  5. 如果存在,则找到了相对应的两个值的下标
  6. 如果不存在,则继续;遍历完都没有,则表明不存在这么两个数
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap();
        for(int i = 0;i < nums.length;i++){
            int key = target - nums[i];
            if(map.containsKey(key)){
                return new int[]{i,map.get(key)};
            }else{
                map.put(nums[i],i);
            }
        }
        throw new IllegalArgumentException("No two sum solution");      
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值