Leetcode 1. Two Sum

28 篇文章 0 订阅
14 篇文章 0 订阅

题目描述:给定一个列表,返回一个数组中两个数相加为target的下标索引。

题目链接:Leetcode 1. Two Sum

开始我的思路是先排序,然后双指针向中间移动,然后记录此时的值,再到原数组去寻找对应值下标注意处理相同值的情况。
正确的思路就是利用hashmap来记target-nums[idx]当出现的数在哈希表内时,证明已经找到了结果了。
一般数组的题目都是用哈希表空间换时间的思想来得出结果,或者维护队列、维护单调栈、维护滑动窗口、维护插入顺序的哈希表接可以得出结果了。

代码如下

import java.util.Arrays;
import java.util.HashMap;
class Solution {
    public int[] twoSum(int[] nums, int target) {
        if (nums.length < 2){
            return null;
        }
        int[] ans = new int[2];
        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(nums.length);
        for (int idx = 0; idx < nums.length; idx++) {
            int res = target - nums[idx];  //下一个要寻找的值
            if (hm.containsKey(nums[idx])==true) { //证明这个idx和hm存储的idx就是答案
                ans[0] = hm.get(nums[idx]);;
                ans[1] = idx;
                
            } else {
                hm.put(res, idx);
            }
        }
        return ans;
    }
}

#第一次的做法

import java.util.Arrays;
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2];
        int[] numNew = new int[nums.length];
        System.arraycopy(nums, 0, numNew, 0, nums.length);
        Arrays.sort(numNew);
        int l = 0;
        int r = nums.length - 1;
        int currSum;
        while (l < r) {
            currSum = numNew[l] + numNew[r];
            if (currSum < target) {
                l++;
            } else if (currSum > target) {
                r--;
            } else {
                boolean flag = true; 
                for (int i = 0; i < nums.length; i++) {
                    if ((nums[i] == numNew[l] || nums[i] == numNew[r]) && flag==true) {

                        ans[0] = i;  //左边index
                        flag = false;
                    } else if ((nums[i] == numNew[r] || nums[i] == numNew[l]) && flag==false) {
                        ans[1] = i; // 右边
                    }
                }
                return ans;
            }
        }
        return null;
    }
}

参考链接

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值