1. 程式人生 > >LeetCode-Algorithms #001 Two Sum, Database #175 Combine Two Tables

LeetCode-Algorithms #001 Two Sum, Database #175 Combine Two Tables

最近兩週一直感覺學習比較鬆懈, 打算加大一點強度, 從今天開始, 希望能在每天正常進度完成後在LeetCode上選一兩題寫一寫, 同時學習一下高手的做法.

LeetCode - Algorithms #001 Two Sum

給定一個整數陣列, 找出其中兩個元素, 使其和等於目標值, 返回這兩個元素在原陣列中的索引組成的陣列. 可以假設有且只有一組正解, 且每個元素只能使用一次.

我的思路:

其實想不到什麼好的方法, 遍歷就好, 非常素樸的回答:

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
3 //根據題目設定, nums的長度必大於等於2, 所以也不用考慮什麼特殊情況 4 //結論所需的兩個索引, i從0開始遍歷, j從1開始遍歷 5 int i = 0,j = 1; 6 outer: for(i = 0; i < nums.length - 1; i++){ 7 for(j = i + 1; j < nums.length; j++){ 8 //找到答案就跳出外迴圈 9 if(nums[i] + nums[j] == target){
10 break outer; 11 } 12 } 13 } 14 //把答案裝進陣列然後返回 15 int[] ans = {i,j}; 16 return ans; 17 } 18 }

結果順利通過, 用時28ms, 只有30%的使用者比我還慢, 看來是寫得很差了