1. Two Sum - easy

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);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容