LeetCode--Array--Two sum (Easy)

1.Two sum (Easy)

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].

solution

题意是给定一个int数组nums和一个整数target,在nums里面找到两数之和为target的数,并返回两数的数组索引。假定nums数组里面只有唯一的一组结果,且同一个数字只能使用一次。

1.最容易想到的暴力算法,也就是我起初想到的!!!

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] indices = 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)
                {
                    indices[0] = i;
                    indices[1] = j;
                    return indices;
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

2.速度更快的解法,HashMap

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> m = new HashMap<Integer,Integer>();
        for (int i = 0; i < nums.length; i++)
        {
            int complement = target - nums[i];
            if (m.containsKey(complement))
                return new int[] {m.get(complement),i};
            m.put(nums[i],i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

reference
https://leetcode.com/articles/two-sum/

总结

第一种暴力算法就是先取一个数,然后用这个数依次与后面的每一个数相加求和,若和与target相等,则将这两个数的数组索引加入到一个新的int数组中,然后返回这个int数组。time complexity:O(n^2),space complexity:O(1)



第二种使用HashMap的方法起初不太容易想到。基本思路是将数组值作为键,索引作为值。是先创建一个hashmap,然后遍历数组nums,如果hashmap中已经存在complement=target-nums[i]这个元素,则将complement键对应的值(即数组索引),和i存到一个新的int数组里面并返回;若果不存在,则将nums[i],i分别作为键与值存到hashmap中去。如果遍历完数组没有找到相应的结果,则抛出异常。time complexity:O(n),space complexity:O(n)



Notes
1.数组值和下标互换是一种常用的技巧,不过只对整数有用;

原文地址:https://www.cnblogs.com/victorxiao/p/11135576.html

时间: 2024-07-30 22:33:20

LeetCode--Array--Two sum (Easy)的相关文章

Leetcode 1. Two Sum (Easy)

Description 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

Leetcode: Split Array Largest Sum

Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. Note: Given m satisfies the following cons

[array] leetcode - 39. Combination Sum - Medium

leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from

[array] leetcode - 40. Combination Sum II - Medium

leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combinat

[LeetCode] 437. Path Sum III_ Easy tag: DFS

You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to

LeetCode --- 1. Two Sum

题目链接: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. Plea

LeetCode:Range Sum Query - Immutable - 数组指定区间内的元素和

1.题目名称 Range Sum Query(数组指定区间内的元素和) 2.题目地址 https://leetcode.com/problems/range-sum-query-immutable/ 3.题目内容 英文:Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 中文:给定一个数组nums,求出索引i和j之间元素的和,i一定是小于或等于j

Java for LeetCode 216 Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. Ensure that numbers within the set are sorted in ascending order. Example 1

【LeetCode OJ】Sum Root to Leaf Numbers

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 # Definition for a  binary tree node # class TreeNode: #     def __init__(self, x): #         self.val = x #         self.left = No