Java [leetcode 1] Two Sum

來源:互聯網
上載者:User

標籤:

小二終於開通部落格了,真是高興。最近在看Java,所以就拿leetcode練練手了。以後我會將自己解體過程中的思路寫下來,分享給大家,其中有我自己原創的部分,也有參考別人的代碼加入自己理解的部分,希望大家看了多提意見,一塊加油。

問題描述:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

解體思路:

設立一個HashMap,其中索引值key為數組中數值,對應值value則為該數組下標值。

從數組最開始往後遍曆,每次求出該值對應target-numbers[i]的值在HashMap中是否存在。如果該值已經存在,那麼則找到兩個值的和為target值,返回即可;如果該值不存在,則把(numbers[i], i)放入HashMap中。

整個演算法的時間複雜度為O(n)。

代碼如下:

 1 public class Solution { 2     public int[] twoSum(int[] numbers, int target) {         3         Map<Integer, Integer> map = new HashMap<Integer, Integer>(numbers.length * 2); 4         int[] results = new int[2]; 5           6         for(int i = 0; i < numbers.length; i++){ 7             Integer temp1 = map.get(target - numbers[i]); 8             if(temp1 == null){ 9                 map.put(numbers[i], i);10             }11             else{12                 results[0] = i + 1;13                 results[1] = temp1 + 1;14                 if(results[0] > results[1]){15                     int temp2 = results[0];16                     results[0] = results[1];17                     results[1] = temp2;18                 }19                 return results;20             }21         }   22         return null;      23     }24 }

 

 

Java [leetcode 1] Two Sum

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.