开始刷题了

开启我的csdn之旅

真正意义上的第一篇博客

虽然很早就申请了账号,但是一直都是膜拜大神的各种文章。今天借着刷LeetCode的冬风,开启我的记录之旅。希望这也能督促我一直写下去,一直有收获吧。下面就开始正文

LeetCode one——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, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

还没什么深刻理解,等有理解了再来补充。下面先附上代码。

代码

//Java
public class TwoSum{
	public int[] twoSum(int[]nums,int target) {
		HashMap<Integer,Integer> m=new HashMap<>();
		int []res=new int[2];
		for(int i=0;i<nums.length;++i) {
			m.put(nums[i], i);
		}
		for(int i=0;i<nums.length;++i) {
			int num=target-nums[i];
			if(m.containsKey(num)&&m.get(num)!=i) {
				res[0]=i;
				res[1]=m.get(num);	
				break;
			}
		}
		return res;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42123213/article/details/87876080