Two Sum

Two Sum

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 1:

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

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

note
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.

Tags: Array,HashTable

解读题意

给定一个数组,数组中某两个数加起来等于指定数,求这两个数的下标。

思路1

假设nums为该数组,target为指定数

  1. 遍历循环每个元素x,找出是否有能够满足target-x的另一个值
class Solution { 

    public int[] twoSum(int[] nums, int target) {

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

        throw new IllegalArgumentException("No two sum solution");
    }
}

分析:

  • Time complexity:O(n^2),外层循环n次,内层循环n-1次,所以时间复杂度为O(n^2)
  • Space complexity:O(1),空间负责度为常数

思路2

思路1用了最暴力循环的方式,两次循环找出了答案,时间复杂度为O(n^2),但是有更好的方法来解决:使用HashMap作为存储。key为当前值,value为索引。此时要先判断target - nums[i] = 9 - 2 = 7是否存在于map中,若不存在,则插入键值key = 2,value = 0;之后i = 1,num[1] = 7,此时9 - 7 = 2,nums[0] = 2已经存在于map中,那么value = 0 = map.get(2)取出值作为第一个返回值,当前i作为第二个返回值。

class Solution { 
   public int[] twoSum(int[] nums, int target) {

        Map<Integer,Integer> map = new HashMap<>();
        int n = nums.length;
        for(int i=0;i<n;i++){
            int sub = target - nums[i];
            if(map.containsKey(sub))
                return new int[]{map.get(sub),i};
            map.put(nums[i],i);
        }

        throw new IllegalArgumentException("No two sum solution");
    }
}

分析:

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

leetCode汇总:https://blog.youkuaiyun.com/qingtian_1993/article/details/80588941

项目源码,欢迎star:https://github.com/mcrwayfun/java-leet-code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值