[LeetCode]1. Two Sum

1. Two Sum

一、题目

Problem Description:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:
2 < = n u m s . l e n g t h < = 1 0 3 2 <= nums.length <= 10^3 2<=nums.length<=103
− 1 0 9 < = n u m s [ i ] < = 1 0 9 -10^9 <= nums[i] <= 10^9 109<=nums[i]<=109
− 1 0 9 < = t a r g e t < = 1 0 9 -10^9 <= target <= 10^9 109<=target<=109
Only one valid answer exists.

二、题解

  • 在给定数组中找到两数之和为目标值的唯一解,结果返回2个数字的下标。

2.1 Approach #1 : Brute Force

暴力破解方法想法很简单,也很容易实现。两个for循环遍历所有可能结果的数字对,找到两数之和等于目标值,返回两数所对应的索引。

此解法易于理解,但时间复杂度较高。

Time complexity : O ( 2 n ) O(2^n) O(2n)
Space complexity : O ( 1 ) O(1) O(1)

//Brute Force
//Time complexity : O(n^2); Space complexity : O(1)
class Solution {
    public static 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;
                	res[1] = j;
					return res;
                }
            }
        }
        return res;
    }
}

2.2 Approach #2 : Hash Table

此题最优解法的时间复杂度为 O ( n ) O(n) O(n)
顺序扫描数组,对每一个元素,在map中找到和为目标值的另一个数。如果找到了,直接返回2个数字的下标即可;如果没找到将这个数以<key = nums[i], value = i>键值对的形式存入map中,等到扫描到另一个数,再取出索引(value值)返回即可

键值对形式:<key = 数组元素值, value = 数组元素值对应的索引>,即<key = nums[i], value = i>

注:理想情况下,HashMap的增、删、改、查等操作的时间复杂度都为 O ( 1 ) O(1) O(1)

Time complexity : O ( n ) O(n) O(n)
Space complexity : O ( n ) O(n) O(n)

//Hash Table
//Time complexity : O(n); Space complexity : O(n)
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] res = new int[2];
        for(int i = 0; i < nums.length; i++){
            int temp = target - nums[i];
            if(map.containsKey(temp)){
                res[0] = map.get(temp);
                res[1] = i;
                return res;
            }else{
                map.put(nums[i], i);
            }
        }
        return res;
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值