0.题记
Bob今天开始要强势回归Leetcode刷题啦撒花撒花LOL。
作为一名即将研二的学生党,正式开始了实习狗的生涯,平时加班不多,正是刷题解闷的大好机会啊O(∩_∩)O哈哈~
给自己定个刷题计划吧:
第一阶段(2个月):从今天8月6号开始到10月6号,按照leetcode上面题目顺序从第1题开始刷,完成100题,每题刷完都写到CSDN博客上面。
第二阶段:看看第一阶段刷题效果再说啦。
Ready?Go!
1.题目
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
2.解法
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
@SuppressWarnings("unused")
int nSize = nums.length;
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
Integer temp = 0;
for(int i = 0; i < nSize; i++){
temp = target - nums[i];
if(m.containsKey(temp)){
res[0] = m.get(temp);
res[1] = i;
}
m.put(nums[i], i);
}
return res;
}
}