轻车熟路
两数之和
http://www.nowcoder.com/questionTerminal/20ef0972485e41019e39543e8e895b7f
思路1:暴力组合
import java.util.*;
public class Solution {
/**
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] numbers, int target) {
// write code here
if(numbers==null || numbers.length<2) return null;
int left = 0;
while(left<=numbers.length-1){
int right = left+1;
while(right<=numbers.length-1){
if((numbers[left]+numbers[right])==target){
return new int[]{++left,++right};
}
right++;
}
left++;
}
return null;
}
}思路2:空间换时间(注意数组中元素重复的情况)
1、第一次遍历元素入map
2、第二次左到右遍历,寻找另一半是否存在于map中
查看8道真题和解析
美的集团公司福利 816人发布