LeetCode刷题日记之 01两数之和

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

法一(暴力枚举法):

我的答案:

//暴力枚举法
class Solution {
    public int[] twoSum(int[] nums, int target) {    
        for(int i=0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
               int sum=nums[i]+nums[j];
                if(target==sum){
                    return new int[]{i, j};
                }
            }
        }
         return new int[0];
    }
}

官方答案:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }
}

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

复杂度分析:

时间复杂度:O(N^2),其中 NN 是数组中的元素数量。最坏情况下数组中任意两个数都要被匹配一次。

空间复杂度:O(1)。

法二(哈希表)重点:

  1. 首先创建一个hash表
    Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
  2. 其次使用for循环遍历nums数组中的元素
     for(int i=0;i<nums.length;i++)
  3. 如果hash表中存在target-nums[i]的值则代表已经找到要找的内容,将其输出
     if(hashtable.containsKey(target-nums[i])){
                     return new int[]{hashtable.get(target-nums[i]),i};
                 }
  4. 若hash表中不存在该元素,将元素存入hash表中
     hashtable.put(nums[i],i);   

图解示例:

第一步:nums[]={4,9,11,4}  target=15

nums[]
num中的数值49114
位置0123
创建Hash列表
key
value

第二步:

遍历nums
num中的数值49114
位置0123
创建Hash列表
key49
value01

第三步:

当前值num[i]=11,target-nums[i]=4在hash表中存在

num中的数值49114
位置0123
target-nums[i]=4在hash表中存在
key49
value01

使用hashtable.get(target-nums[i])返回value值。值得注意的是:hash表中的key元素是nums的数值,value元素是在数组中的位置。

完整代码如下:

class Solution {
    public int[] twoSum(int[] nums, int target) {    
        //法二:hash表
         Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
         for(int i=0;i<nums.length;i++){
             if(hashtable.containsKey(target-nums[i])){
                 return new int[]{hashtable.get(target-nums[i]),i};
             }
             hashtable.put(nums[i],i);   
         }
    return new int[0];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值