您的位置:首页 > 其它

LeetCode 1.Two Sum 解题报告

2016-02-18 17:23 387 查看


1. Two Sum

My Submissions

Question

Total Accepted: 188053 Total
Submissions: 888224 Difficulty: Medium

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


UPDATE (2016/2/13):

The return format had been changed to zero-based indices. Please read the above updated description carefully.

Subscribe to see which companies asked this question

Show Tags

Show Similar Problems

Have you met this question in a real interview?
Yes

No

Discuss

《编程之美》上的一道原题,如果用暴力枚举的方法,时间复杂度将是n的平方。但是如果借助hash技术可以巧妙的将平方复杂度降级。

我的AC代码

public class TwoSum {

	public static void main(String[] args) {
		int[] a = { 2, 7, 11, 15 };
		System.out.println(twoSum(a, 9));
	}
	
	public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        int n2;
        Integer idx;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length);
        
        for (int i = 0; i < nums.length; i++) {
			map.put(nums[i], i);
		}
        for (int i = 0; i < nums.length - 1; i++) {
			n2 = target - nums[i];
			idx = map.get(n2);
			if(idx != null && idx > i){
				result[0] = i;
				result[1] = idx;
				break;
			}
		}
        return result;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: