package com.java.tencent; import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map; public class T_1_twoSum { /*初级解法*/
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i=0;i<nums.length-1;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i] + nums[j]==target){
result[0] = i;
result[1] = j;
break;
}
}
}
return result;
} /*中级解法*/
public int[] twoSum_yh(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
map.put(nums[i], i);
}
for(int i = 0; i < nums.length; i++){
int complement = target - nums[i];
if(map.containsKey(complement) && map.get(complement) != i){
return new int[]{ i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
} /*高级解法*/
public int[] twoSum_yh_max(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
int complement = target - nums[i];
if(map.containsKey(complement)){
return new int[]{map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
} public static void main(String[] args) {
/*nums数组任意两个值等于target,返回数据在nums里的位置*/
int[] nums = {3,2,3};
int target = 6;
T_1_twoSum aa = new T_1_twoSum();
System.out.println(Arrays.toString(aa.twoSum(nums, target))); System.out.println(Arrays.toString(aa.twoSum_yh(nums, target))); System.out.println(Arrays.toString(aa.twoSum_yh_max(nums, target)));
} }
结果:[0,2]
由于循环次数的不同,效率也不同,高级解法的效率最佳。
以上多种解法,看看各位处于什么解题思路上。
希望能帮助大家提高代码水平。