【LeetCode】1. Two Sum 解题报告



转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280


Subject

出处: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.

Example:

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

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

return [0, 1].


Explain

该题目给定一个int型数组,和一个target数值。要求找出数组中两个下标对应的数字之和等于target。

返回两个下标组成的数组。


Solution

solution 1

最笨的方法就是循环嵌套。

public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];

        if (nums == null || nums.length == 0) {
            return result;
        }

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }

该方法时间复杂度较高,O(n2)。

空间复杂度是O(1)。


solution 2

虽然方法一通过了测试,但是时间复杂度较高。

然后看到该题目的提示标签是【Array】【Hash Table】,就想到使用HashMap来存储下标和值。

/**
     * 使用HashMap存储 <br />
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum2(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                if (i > map.get(target - nums[i])) {
                    result[0] = map.get(target - nums[i]);
                    result[1] = i;
                } else {
                    result[0] = i;
                    result[1] = map.get(target - nums[i]);
                }
            } else {
                map.put(nums[i], i);
            }
        }
        return result;
    }

注意将 nums[i] 作为key,将下标 i 作为value。

判断map里面是否存在 target-nums[i] 这个key。



bingo~~

时间: 2024-08-27 00:42:00

【LeetCode】1. Two Sum 解题报告的相关文章

LeetCode: Minimum Path Sum 解题报告

Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. SOLUTION 1: 相当基础

LeetCode 1. Two Sum 解题报告

题意: 数组nums中,有两个元素的和是target,找出这两个元素的位置. 思路: 维护一个map,用数组的元素的值做key,用元素的位置做value.遍历nums,对每个num来说,如果map[target - num] 有值的话,就返回map[target - num]和num的位置,如果没有找到的话,就把num插入到map中,map[num] = index.时间复杂度O(nlogn). C++ Code: class Solution { public: vector<int> tw

LeetCode: Pascal&#39;s Triangle 解题报告

Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] SOLUTION 1:很easy的题.注意记得把List加到ret中.比较简单,每一行的每一个元素有这个规律:1. 左右2边的是1.i, j 表示行,列坐标.2.

[LeetCode]Longest Valid Parentheses, 解题报告

题目 Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example i

【LeetCode】Insert Interval 解题报告

[题目] Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and m

LeetCode: Combination Sum 解题报告

Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Question Solution Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The

LeetCode: Unique Paths II 解题报告

Unique Paths II Total Accepted: 31019 Total Submissions: 110866My Submissions Question Solution Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty spac

【LeetCode】3Sum Closest 解题报告

[题目] Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {

【LeetCode】Symmetric Tree 解题报告

Symmetric Tree 解题报告 [LeetCode] https://leetcode.com/problems/symmetric-tree/ Total Accepted: 106639 Total Submissions: 313969 Difficulty: Easy Question Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For

【LeetCode】Next Permutation 解题报告

[题目] Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The repl