1 Packagecom.java.tencent;2 3 ImportJava.lang.reflect.Array;4 Importjava.util.Arrays;5 ImportJava.util.HashMap;6 ImportJava.util.Map;7 8 Public classT_1_twosum {9 Ten /*Primary Solution*/ One Public int[] Twosum (int[] Nums,inttarget) { A int[] result =New int[2]; - for(inti=0;i<nums.length-1;i++){ - for(intj=i+1;j<nums.length;j++){ the if(Nums[i] + nums[j]==target) { -Result[0] =i; -RESULT[1] =J; - Break; + } - } + } A returnresult; at } - - /*Intermediate Solution*/ - Public int[] Twosum_yh (int[] Nums,inttarget) { -map<integer,integer> map =NewHashmap<integer,integer>(); - for(inti = 0; i < nums.length; i++){ in Map.put (Nums[i], i); - } to for(inti = 0; i < nums.length; i++){ + intcomplement = target-Nums[i]; - if(Map.containskey (complement) && map.get (complement)! =i) { the return New int[]{I, Map.get (complement)}; * } $ }Panax Notoginseng Throw NewIllegalArgumentException ("No, Sum solution"); - } the + /*Advanced Solution*/ A Public int[] Twosum_yh_max (int[] Nums,inttarget) { themap<integer,integer> map =NewHashmap<integer,integer>(); + for(inti = 0; i < nums.length; i++){ - intcomplement = target-Nums[i]; $ if(Map.containskey (complement)) { $ return New int[]{map.get (complement), i}; - } - Map.put (Nums[i], i); the } - Throw NewIllegalArgumentException ("No, Sum solution");Wuyi } the - Public Static voidMain (string[] args) { Wu /*nums array Any two values equal to target, returns the position of the data in the Nums*/ - int[] Nums = {3,2,3}; About inttarget = 6; $T_1_twosum AA =Newt_1_twosum (); - System.out.println (arrays.tostring (Aa.twosum (nums, Target)); - - System.out.println (arrays.tostring (Aa.twosum_yh (nums, Target)); A + System.out.println (arrays.tostring (Aa.twosum_yh_max (nums, Target)); the } - $}
Results: [0,2]
Because of the different cycle times, the efficiency is also different, the efficiency of the advanced solution is the best.
The above various solutions, see you are in what problem-solving ideas.
Hope to help you improve the code level.
An array of nums, where any two value equals the given value of target, returns the position of the two values in Nums