[LeetCode]1. 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].

解法1:暴力

这道题最原始的方法当然是暴力解法,两个for循环就能解决问题,这样的时间复杂度是O(n2),空间复杂度是O(1).

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] arrSum = new int[2];
        //如果数组长度小于2就不用继续往下了
        if(nums==null||nums.length<2){
            return arrSum;
        }
        for(int i=0;i<nums.length-1;i++){
            for(int j=i+1;j<nums.length;j++){
                     if(nums[i]+nums[j]==target){
                            arrSum[0]=i;
                            arrSum[1]=j;
                            
                     }

            }
<span style="white-space:pre">		</span>
        }
<span style="white-space:pre">	</span>return arrSum;
     }
    
}
解法2:双指针

我们知道如果我们用两个指针来进行一头一尾扫描的话,那么我们是可以得到所需要的两个index的,所以只需要对数组进行一下排序即可,然后用双指针来进行扫描,把扫到的index放进新数组返回即可。时间复杂度O(nlogn+n)=O(nlogn),空间复杂度O(1).注:我写的时候没有考虑返回之前数组的index,所以不能直接copy此代码submit,你需要自己再loop一遍原来的数组再取得所需要的index

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] arrSum = new int[2];
        if(nums==null||nums.length<2){
            return arrSum;
        }
        Arrays.sort(nums);
        int left=0;
        int right=nums.length-1;
        while(left<right){
            if(nums[left]+nums[right]==target){
                arrSum[0]=left;
                arrSum[1]=right;
                break;
            }
            if(nums[left]+nums[right]<target){
                left++;
                continue;
            }
            if(nums[left]+nums[right]>target){
                right--;
                continue;
            }
        }
        return arrSum;
    }
}
解法3:哈希表

哈希表的解法就是把index和他所在的值放入map中,然后如果能够找到target减去当前索引值的差存在于哈希表中,那么就把这两个索引放入到新数组中返回。因为只需要遍历一遍数组,所以时间复杂度是O(n),空间复杂度也是O(n)

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] arrSum = new int[2];
        if(nums==null||nums.length<2){
            return arrSum;
        }
<span style="white-space:pre">	</span>//我们把key设定为nums的值,value为索引,因为要判断target减去索引所在的值,key调用会方便一些
        HashMap<Integer,Integer> ht = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            if(!ht.containsKey(target-nums[i])){
                ht.put(nums[i],i);
            }else{
                arrSum[0]=ht.get(target-nums[i]);
                arrSum[1]=i;
                break;
            }
        }
        return arrSum;
    }
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值