【LeetCode】Two Sum 题解报告

来源:互联网 发布:画电气图软件 编辑:程序博客网 时间:2024/06/02 03:52

[题目]
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.

For Example: Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

[解析]
这是一道简单题,题目很好理解,就是在一个数组中找到两个数的和等于所要求的值,于是最直接想法,两重循环求得结果。
- 解法1:

public static int[] twoSum(int[] nums, int target){    if(nums == null || nums.length < 2)        return null;    int[] res = new int[2];    boolean flag = true;    for(int i=0;i<nums.length&&flag;i++){        int tmp = target - nums[i];        for(int j=i+1;j<nums.length;j++){            if(nums[j] == tmp){                res[0] = i;                res[1] = j;                flag = false;                break;            }        }    }    if(flag)        return null;    else        return res;}

上面的时间效率是O(n^2).很明显,算法还可以更优。
- 解法2:
将数组中的元素存放到一个HashMap中,数组的值作为key,数组的下标作为value。利用HashMap的O(1)的查找效率可以得到更高效率的解法,总的时间效率为O(n).

public static int[] twoSum1(int[] nums, int target){    if(nums == null || nums.length < 2)        return null;    HashMap<Integer, Integer> hashNum = new HashMap<Integer, Integer>();    for(int i=0;i<nums.length;i++){        Integer n = hashNum.get(nums[i]);        if(n == null)hashNum.put(nums[i], i);        n = hashNum.get(target - nums[i]);        if(n != null && n<i){            return new int[]{n,i};        }    }    return null;}

这里需要注意的是,由于HashMap中的元素不能重复,所以相同元素仅存一次。这里做了处理,即仅存放重复元素第一次出现的那个元素。如果target的值刚好是两个重复元素的和,也不会受到影响。
例如,nums = {3,4,3,5},target = 6,输出的结果是[0,2].

0 0
原创粉丝点击