1. Two Sum

刷题笔记

1.Two Sum

题目

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.
在这里插入图片描述

思路

  1. 两层循环判断两数加和是否等于target即可。

代码实现

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        int[] ans = new int[2];
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (nums[i] + nums[j] == target) {
                    ans[0] = i;
                    ans[1] = j;
                    return ans;
                } else {
                    continue;
                }
            }
        }
        return ans;
    }
}

这种解法速度很快,占用内存较多:
在这里插入图片描述
再来看只需要遍历一遍数组的方法:

class Solution {
public int[] twoSum(int[] numbers, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; map.put(numbers[i], i++)) 
            if (map.containsKey(target - numbers[i])) 
                return new int[]{map.get(target - numbers[i]),i};
        return new int[]{0,0};
    }
}

这种解法保证只用遍历一遍数组,解法思路如下:

  1. 首先创建一个hashmap,键值对的类型都是interger。
  2. 然后对数组进行遍历,精巧的地方在于,在遍历最开始的时候,hashmap是空的,相当于循环只是在往hashmap中放入键值对,而判断语句判断target-numbers[i]这个键在map中存不存在,如果存在则说明匹配成功,则可以反悔两个下标;匹配不成功则继续循环放入键值对。
  3. 这种方法的运行结果很成功,改善了占用空间的问题。

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值