1 Two Sum (Array)
生活随笔
收集整理的這篇文章主要介紹了
1 Two Sum (Array)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
老的方法O(n2)不太好
System.out array的時候不能直接顯示,要用Arrays.toString() 轉換下
?
1 //老的: 2 3 import java.util.Arrays; 4 5 public class Twosum { 6 public static void main(String[] args) { 7 Solution s = new Solution(); 8 int[] nums = {2 ,7 ,11, 15}; 9 int[] result = s.twoSum(nums, 9); 10 System.out.println(Arrays.toString(result)); 11 12 } 13 14 } 15 16 class Solution { 17 public int[] twoSum(int[] nums, int target) { 18 for (int i = 0; i < nums.length; i++) { 19 for (int j = i+1; j < nums.length; j++) { 20 if (nums[i] + nums[j] == target) { 21 int[] result = {i, j}; 22 return result; 23 } 24 } 25 } 26 return nums; 27 28 } 29 } 30 31 32 33 34 //96%: 35 class Solution { 36 public int[] twoSum(int[] nums, int target) { 37 HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); 38 int[] res = new int[2]; 39 for (int i = 0; i < nums.length; ++i) { 40 if (m.containsKey(target - nums[i])) { 41 res[1] = i; 42 res[0] = m.get(target - nums[i]); 43 break; 44 } 45 m.put(nums[i], i); 46 } 47 return res; 48 } 49 }?
轉載于:https://www.cnblogs.com/goPanama/p/9353357.html
總結
以上是生活随笔為你收集整理的1 Two Sum (Array)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 赵薇夫妇被上交所处分 “小燕子”到底怎么
- 下一篇: 各银行信用卡宽限期几天