Two Sum

来源:互联网 发布:成都黑马程序员怎么样 编辑:程序博客网 时间:2024/06/14 04:26

题目:

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

其实O(n^2)的算法是个程序员应该都能写出来,如下:

public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] a = new int[2];        int flag = 0;        int temp = nums.length;        for (int i = 0;i < temp-1;i++) {            for (int j = i+1;j < temp;j++) {                if (nums[i] + nums[j] == target) {                    a[0] = i+1;                    a[1] = j+1;                    flag = 1;                    break;                }            }            if (flag == 1) {                break;            }        }        return a;    }}

后来看了下讨论区,有O(n)的算法。首先是利用了Java HashMap的get()和put()的时间复杂度在没有冲突的情况下为O(1)的特性,然后因为a + b = target, 遍历的时候用target-b做键,下标做值,放入哈希表,又用a做键去找,能找到则a = target - b,即a + b = target。代码如下:

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



0 0
原创粉丝点击