1. Two Sum

来源:互联网 发布:如何运行协同过滤算法 编辑:程序博客网 时间:2024/06/05 02:50

这个题还是比较简单的,题目要求需要返回两个值的下标,用一个HashMap表示就行。该题目的时间复杂度不是O(n),因为for循环内有HashMap的查找开销。

class Solution {    public int[] twoSum(int[] nums, int target) {        if (nums.length < 2){            return null;        }        Set<Integer> set = new HashSet<>();        Map<Integer, Integer> map = new HashMap<>();        int[] ret = new int[2];        for (int i = 0; i < nums.length; ++ i){            if (set.contains(target-nums[i])){                ret[0] = map.get(target - nums[i]);                ret[1] = i;                return ret;            }            set.add(nums[i]);            map.put(nums[i], i);        }        return null;    }}

原创粉丝点击