题解 | #两数之和#三种方法实现(HashMap,For循环,有序列表的indexOf)
两数之和
http://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
import java.util.*;
//三种方法
//第一种:借助hashmap
//第二种:常规for循环
//第三种:接触有序列表的indexOf方法查找序号
public class Solution {
/**
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] numbers, int target) {
//第一种:借助hashmap
int len = numbers.length;
HashMap<Integer,Integer> hm = new HashMap<>(len);
for ( int i =0;i<len ;i++){
int other = target - numbers[i];
if( hm.containsKey(other)){
return new int[]{hm.get(other)+1,i+1};
}
hm.put(numbers[i],i);
}
return new int[]{0,0};
//第二种:常规for循环
// int len = numbers.length;
// for( int i=0;i<len-1;i++){
// for(int j=i+1;j<len;j++){
// if(numbers[i] + numbers[j] == target){
// return new int[]{i+1,j+1};
// }
// }
// }
// return new int[]{0,0};
//第三种:接触有序列表的indexOf方法查找序号
// ArrayList<Integer> al = new ArrayList<Integer>(numbers.length);
// int[] res = new int[2];
// for(int x: numbers){
// al.add(x);
// }
// for(int i = 0;i<numbers.length;i++){
// int other = target -numbers[i];
// int index = al.indexOf(other);
// if(index == -1 || index == i){
// continue;
// }else{
// if( i> index){
// res[0] = index+1;
// res[1] = i+1;
// }else{
// res[0] = i+1;
// res[1] = index+1;
// }
// break;
// }
// }
// return res;
}
}
查看8道真题和解析
腾讯成长空间 1100人发布