美文网首页
1. Two Sum - easy

1. Two Sum - easy

作者: 沉睡至夏 | 来源:发表于2016-10-20 07:08 被阅读14次

They are actually the same problem.
2-sum:
my code:
比较简单的一道题。扫过每个数,寻找与这个数和为target,并且已经扫过的数。如果存在就return,不存在就放入map继续扫。

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            int part = target - nums[i];
            if (map.containsKey(part))  
                return new int[]{map.get(part),i};
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No Solution");
    }
}

分析:
running time : around O(nlgn), "lgn" is the time for put and get. put and get usually O(1)-O(n), depends on the situation. JDK 8, average around lgn.
space: O(n);

相关文章

网友评论

      本文标题:1. Two Sum - easy

      本文链接:https://www.haomeiwen.com/subject/akkfuttx.html