1 package com.java.tencent; 2 3 import java.lang.reflect.Array; 4 import java.util.Arrays; 5 import java.util.HashMap; 6 import java.util.Map; 7 8 public class T_1_twoSum { 9 10 /*初级解法*/ 11 public int[] twoSum(int[] nums, int target) { 12 int[] result = new int[2]; 13 for(int i=0;i<nums.length-1;i++){ 14 for(int j=i+1;j<nums.length;j++){ 15 if(nums[i] + nums[j]==target){ 16 result[0] = i; 17 result[1] = j; 18 break; 19 } 20 } 21 } 22 return result; 23 } 24 25 /*中级解法*/ 26 public int[] twoSum_yh(int[] nums, int target) { 27 Map<Integer,Integer> map = new HashMap<Integer,Integer>(); 28 for(int i = 0; i < nums.length; i++){ 29 map.put(nums[i], i); 30 } 31 for(int i = 0; i < nums.length; i++){ 32 int complement = target - nums[i]; 33 if(map.containsKey(complement) && map.get(complement) != i){ 34 return new int[]{ i, map.get(complement) }; 35 } 36 } 37 throw new IllegalArgumentException("No two sum solution"); 38 } 39 40 /*高级解法*/ 41 public int[] twoSum_yh_max(int[] nums, int target) { 42 Map<Integer,Integer> map = new HashMap<Integer,Integer>(); 43 for(int i = 0; i < nums.length; i++){ 44 int complement = target - nums[i]; 45 if(map.containsKey(complement)){ 46 return new int[]{map.get(complement), i }; 47 } 48 map.put(nums[i], i); 49 } 50 throw new IllegalArgumentException("No two sum solution"); 51 } 52 53 public static void main(String[] args) { 54 /*nums数组任意两个值等于target,返回数据在nums里的位置*/ 55 int[] nums = {3,2,3}; 56 int target = 6; 57 T_1_twoSum aa = new T_1_twoSum(); 58 System.out.println(Arrays.toString(aa.twoSum(nums, target))); 59 60 System.out.println(Arrays.toString(aa.twoSum_yh(nums, target))); 61 62 System.out.println(Arrays.toString(aa.twoSum_yh_max(nums, target))); 63 } 64 65 }
结果:[0,2]
由于循环次数的不同,效率也不同,高级解法的效率最佳。
以上多种解法,看看各位处于什么解题思路上。
希望能帮助大家提高代码水平。
原文地址:https://www.cnblogs.com/Monster-World/p/9609686.html
时间: 2024-10-10 10:26:58