码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode(1) Two Sum

时间:2016-02-03 01:52:17      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/two-sum/

 

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

 

今天开始从零单排leetcode, 纪念一些

这题比较简单,但也有几个细节需要注意。这题要求返回数的下标,注意是从1开始。

 

解法一:双指针暴力解法,时间复杂度O(n2),空间O(1)

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

解法2:Hashtable, 时间复杂度O(n), 空间复杂度O(1)

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(nums[i])){
                res[0] = map.get(nums[i])+1;
                res[1] = i+1;
                break;
            }else{
                map.put(target-nums[i], i);
            }
        }
        return res;
    }
}

 

Leetcode(1) Two Sum

标签:

原文地址:http://www.cnblogs.com/xinhuan23/p/5178856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!