leetcode 1. Two Sum

原题链接:1. Two Sum

【思路1-Java】

借用 hashmap,时间复杂度可以降到 O(n),hashmap 中 key 为 nums 数组元素的值,value 为数组元素对应下标。假如对于第 i 个数 nums[i],如果 hashmap 中包含 target - nums[i]的  key 值,那么说明已经可以找到这样两个和为 target 的数,返回即可,否则,返回 null:

    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++)
            if (hm.containsKey(target - nums[i])) return new int[]{hm.get(target - nums[i]), i};
            else hm.put(nums[i], i);
        return null;
    }
16 / 16  test cases passed. Runtime: 6 ms  Your runtime beats 58.79% of javasubmissions.
【思路2-Java】
 如果不借用 hashmap,直接用 brute force的话,时间复杂度为 O(n2)。我们可以先对 nums 数组进行排序,时间复杂度为O(nlogn),然后用两个指针start 和 end分别指向开头和结尾,在 start < end 范围内进行查找,有下列3中情况:

1. nums[start] + nums[end] = target,那么直接返回 start 和 end

2. nums[start] + nums[end] < target,那么 start++

3. nums[start] + nums[end] > target,那么 end--

如果没找到就返回 null。

但是我们要注意的是,不能直接对原数组进行排序,因为原数组被打乱了,那么原先的下标也就被打乱了,正确的做法是:申请一个同样大小的数组,然后将原数组拷贝到新的数组中,再对新数组进行排序,最后在原数组中找到这两个元素的下标即可:

    public int[] twoSum(int[] nums, int target) {
        int[] sNums = new int[nums.length], res = null;
        System.arraycopy(nums,0,sNums,0,nums.length);
        Arrays.sort(sNums);
        int start = 0, end = nums.length - 1, index = 0;
        while(start < end)
            if (sNums[start] + sNums[end] == target) {res = new int[]{start, end}; break;}
            else if (sNums[start] + sNums[end] < target) start++;
            else end--;
        for (int i = 0; i < nums.length; i++)
            if (sNums[start] == nums[i] || sNums[end] == nums[i]) res[index++] = i;
        return res;
    }
16 / 16  test cases passed. Runtime: 4 ms  Your runtime beats 98.85% of javasubmissions.

欢迎优化!


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值