1. 兩數之和【Leetcode中國,by java】

來源:互聯網
上載者:User

標籤:中國   空間換時間   public   shm   return   target   twosum   except   nta   

給定一個整數數組和一個目標值,找出數組中和為目標值的兩個數。

你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。

樣本:

給定 nums = [2, 7, 11, 15], target = 9因為 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1]

解題:今天發現LeetCode原版網站登不上了,不知道是不是被牆了,只好再轉移陣地。這個題目還是比較簡單的,方法也比較多,先看第一種,暴力解法,雙重迴圈判斷兩個值的和是否與target相等。代碼如下:

 1 class Solution { 2     public int[] twoSum(int[] nums, int target) { 3         int[] result = new int[2]; 4        // Arrays.sort(nums); 5         for(int i = 0; i < nums.length-1; i++){ 6             for(int j = i + 1; j < nums.length; j++ ){ 7                 if(nums[i] + nums[j] == target){ 8                     result[0] = i; 9                     result[1] = j;10                     return result;11                 }12             }13         }14         return null;15     }16 }

也可以用hash表來做,空間換時間。將每個元素與其對應位置放進HashMap,放之前先判斷表內是否已經有存在對應的數能,與之和能為target,有則返回結果,沒有則繼續放。代碼如下:

 1 class Solution { 2     public int[] twoSum(int[] nums, int target) { 3         Map<Integer, Integer>map = new HashMap<Integer,Integer>(); 4         for(int i =0; i < nums.length; i++){ 5             if( map.containsKey(target - nums[i]) ) 6                return new int[]{map.get(target - nums[i]), i}; 7             map.put(nums[i], i); 8         } 9                throw new IllegalArgumentException();10     }11 }

 

1. 兩數之和【Leetcode中國,by java】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.