LeetCode 1 Two Sum

来源:互联网 发布:淘宝购物信用上征信吗 编辑:程序博客网 时间:2024/06/08 16:26

Two Sum

 Total Accepted: 87651 Total Submissions: 497199My Submissions

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

首先想到是两个for循环,执行的时间为O(n*n),发现系统提交上面显示超时,下面为代码:

public int[] twoSum(int[] nums, int target) {int a[] = new int[2];for (int i = 0; i < nums.length; i++)for (int j = 0; j < nums.length; j++) {if (nums[i] + nums[j] == target) {a[0] = i + 1;a[1] = j + 1;}}Arrays.sort(a);return a;}

然后想到先将数组排序,找到<target的最大位置i和<target/2的最大位置j,然后将其两个for循环,其时间复杂度为O(n/2*n/2),还要改进。

最后想到是用hashtable或者hashmap来做,使得时间复杂度为线性的即O(n),下面为代码:

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


0 0
原创粉丝点击