程序员面试的时候,笔试经常会出现leetCode题目,这个系列是整理下leetCode题目解法,也方便自己整理
第一题开始TwoSum
题目:
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].
给了我们一个数组,还有一个目标数target,让我们找到两个数字,使其和为target
思路:创建一个hashMap,将数组的值作为key,数组下标作为value,通过查找target减去对应值是否在map中来得到结果。
解法一:
public int[] solutionNoOne(int[] intArray , int target)
{
HashMap<Integer,Integer> arrayMap = new HashMap<>();
int[] result = new int[2];
for(int i=0;i<=intArray.length-1;i++)
{
arrayMap.put(intArray[i],i);
}
for(int j=0;j<intArray.length-1;j++)
{
if(arrayMap.containsKey(target-intArray[j])&&target-intArray[j]!=j)
{
result[0] = j;
result[1] = target-intArray[j];
break;
}
}
return result;
}
解法二:将两个for循环合并在一起:
public int[] solutionNoOne(int[] intArray , int target)
{
HashMap<Integer,Integer> arrayMap = new HashMap<>();
int[] result = new int[2];
for(int i=0;i<=intArray.length-1;i++)
{
arrayMap.put(intArray[i],i);
}
for(int j=0;j<intArray.length-1;j++)
{
if(arrayMap.containsKey(target-intArray[j])&&target-intArray[j]!=j)
{
result[0] = j;
result[1] = target-intArray[j];
break;
}
}
return result;
}
相关代码github地址:https://github.com/harrypitter/leetCode1-10.git