leetcode题解-1.Two Sum

题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
其实就是从数组里找到两个数,其和为target。注意返回结果是索引而不是数值。
思路一:嵌套循环,毫无疑问,这是最容易被想到的最直接的思路了。没什么好解释的,直接上代码。但是由于嵌套循环,所以时间复杂度很高。

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

思路二:使用HashMap数据结构,用来保存已经读取过的数及其索引。牺牲空间复杂度换取时间复杂度。O(N)。

public int[] twoSum(int[] numbers, int target) {
    int[] result = new int[2];
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < numbers.length; i++) {
        if (map.containsKey(target - numbers[i])) {
            result[1] = i;
            result[0] = map.get(target - numbers[i]);
            return result;
        }
        map.put(numbers[i], i);
    }
    return result;
}

思路三:将数组进行排序,然后使用两个游标指针进行判断。这里需要注意的是在数组进行排序时会使其下标索引发生变化,所以此处使用一个转换技巧,将原数组进行重新编码
nums[i] = nums[i] * n + (nums[i] < 0 ? -i : i);
这样做使得新的数组即包含了其索引值,排序也不会发生变化。可以很好的解决我们的问题。
如:【3,2,-7,9】—》【12,10,-35,45】

public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        for(int i = 0; i < n; i++) 
             nums[i] = nums[i] * n + (nums[i] < 0 ? -i : i);
        Arrays.sort(nums);        
        int lo = 0, hi = n - 1;        
        while (lo < hi) {
            int sum = nums[lo]/n + nums[hi]/n;
            if (sum == target) return new int[]{nums[lo] < 0 ? -nums[lo] % n : nums[lo] % n, nums[hi] < 0 ? -nums[hi] % n : nums[hi] % n};
            if (sum < target)   lo++;
            else                hi--;
        }
        throw new IllegalArgumentException();
    }

以上三种思路耗时越来越短,尤其是方法三使用了编码的思路使得数组排序变为可行方案,大大减少了程序用时。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值