public class Solution {
public int[] twoSum(int[] nums, int target) {
// intuitive O(n^2) approach
for (int i=0; i<nums.length; i++)
for (int j=i+1; j<nums.length; j++)
if (nums[i]+nums[j] == target)
return new int[]{i, j};
// hashmap O(n) approach
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
// check target-nums[i] first, if exists, then return; else put (nums[i], i) into the table
// so that we can avoid putting same key(nums[i]) into the table
// such as the case (1, 2, 4, 4) target=8
for (int i=0; i<nums.length; i++) {
if (map.get(target-nums[i]) != null)
return new int[]{map.get(target-nums[i]), i};
map.put(nums[i], i);
}
return new int[]{};
}
}
Leetcode 1. Two Sum
最新推荐文章于 2019-04-02 16:29:40 发布