思路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中

京公网安备 11010502036488号