01. Two Sum

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

Given an array of integers, returnindicesof the two numbers such that they add up to a specific target.

You may assume that each input would haveexactlyone solution, and you may not use thesameelement twice.

Example:

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

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

分析 && 代码

从头写一遍玩。

这题因为没有排序,所有用一个hashmap来存`<Number, Index>`。 从头到尾走一遍,如果没有遇到过能和当前数组成target的,就把这组信息放入map,否则返回结果

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

O(n)

results matching ""

    No results matching ""