LeetCode-探索-初级算法-数组-9. 两数之和(个人做题记录,不是习题讲解)

50 篇文章 0 订阅
50 篇文章 0 订阅
LeetCode-探索-初级算法-数组-9. 两数之和(个人做题记录,不是习题讲解)
  • 语言:java

  • 思路:两层遍历,寻找两数和等于target的下标

  • 代码(32ms):

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int len = nums.length;
            int[] res = new int[2];
            for(int i = 0;i<len-1;++i){
               for(int j = i+1;j<len;++j){
                   if(nums[i]+nums[j] == target){
                       res[0] = i;
                       res[1] = j;
                       return res;
                   }
               } 
            }
            return null;
        }
    }
    
  • 参考代码1(2ms):利用map记录遍历过的数字,然后如果包含当前数字和过去记录数字之和为target就返回数组。

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            HashMap<Integer, Integer> my_map=new HashMap<>();
            for(int i=0;i<nums.length;i++){
                int complement = target-nums[i];
                if(my_map.containsKey(complement)){
                    return new int[] {i, my_map.get(complement)};
                }
                my_map.put(nums[i],i);
            }
            throw new IllegalArgumentException("No two sum solution");
        }
    }
    
  • 参考代码2(3ms):

    class Solution {
        public int[] twoSum(int[] nums, int target) {
           if(nums == null || nums.length < 2){
                return new int[]{-1,-1};
            }
            int[] res = new int[]{-1,-1};
            HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
            for (int i = 0; i < nums.length ; i++){
                if (map.containsKey(target - nums[i])){
                    res[0] = map.get(target - nums[i]);
                    res[1] = i;
                    return res;
                }
                map.put(nums[i],i);
            }
            return res;
        }
    }
    
  • 参考后重写(3ms):

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int len = nums.length;
            int[] res = new int[2];
            int tmp = 0;
            Map<Integer,Integer> map = new HashMap<Integer,Integer>();
            for(int i = 0;i < len;++i){
                tmp = target - nums[i];
                if(map.containsKey(tmp)){
                    return new int[]{map.get(tmp),i};
                }
                map.put(nums[i],i);
            }
            return null;
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值