Skip to content

1. Two Sum

难度: Easy

刷题内容

原题连接

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

内容描述

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, and you may not use the same element twice.

Example:

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

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

解题方案

思路 1 **- 时间复杂度: O(N)*- 空间复杂度: O(N)***

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


回到顶部