Leetcode Two Sum

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode Two Sum相关的知识,希望对你有一定的参考价值。

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 Two Sum的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(371) Sum of Two Integers

Leetcode Two Sum

1_Two Sum --LeetCode

leetcode371. Sum of Two Integers

LeetCode之371. Sum of Two Integers

LeetCode: 371 Sum of Two Integers(easy)