leetcode java1_Java [leetcode 1] Two Sum

小二终于开通博客了,真是高兴。最近在看Java,所以就拿leetcode练练手了。以后我会将自己解体过程中的思路写下来,分享给大家,其中有我自己原创的部分,也有参考别人的代码加入自己理解的部分,希望大家看了多提意见,一块加油。

问题描述:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

解体思路:

设立一个HashMap,其中键值key为数组中数值,对应值value则为该数组下标值。

从数组最开始往后遍历,每次求出该值对应target-numbers[i]的值在HashMap中是否存在。如果该值已经存在,那么则找到两个值的和为target值,返回即可;如果该值不存在,则把(numbers[i], i)放入HashMap中。

整个算法的时间复杂度为O(n)。

代码如下:

import java.util.*;

public class Solution {

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

Map map = new HashMap(numbers.length * 2);

int[] results = new int[2];

for(int i = 0; i < numbers.length; i++){

Integer temp1 = map.get(target - numbers[i]);

if(temp1 == null){

map.put(numbers[i], i);

}

else{

results[0] = i + 1;

results[1] = temp1 + 1;

if(results[0] > results[1]){

int temp2 = results[0];

results[0] = results[1];

results[1] = temp2;

}

return results;

}

}

return null;

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值