【二刷】1. Two Sum

本文深入探讨了经典的两数之和算法问题,提供了两种解决方案:暴力解法和利用Hashmap的优化方法。暴力解法通过双重循环查找目标值,而优化方案则采用Hashmap实现一次遍历,显著提高效率。

题目:

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.

必须按顺序,第二个比第一个大,返回位置的值

第一种方法: 暴力解法,两次遍历。要注意j+1,因为j比i大

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

第二种方法: 利用Hashmap,把key和value存进去,比较新存入的是否满足 target - 之前的。这样一次遍历就可以了。要注意的是,containsKey 有s而且K大写。

public int[] twoSum(int[] nums, int target) {  
int [] a = new int[2];  
Map <Integer,Integer> map = new HashMap<>();     
for(int i = 0; i<nums.length;i++){
    if(!map.containsKey(target-nums[i])){
        map.put(nums[i],i);
    }else{
        a[0] = map.get(target-nums[i]);
        a[1] = i;
        break;
    }       
}       
   return a;         
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值