LeetCode 1. Two Sum (兩數之和)
阿新 • • 發佈:2017-07-11
ret desc rip twosum 關鍵點 earch pub ++ num
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
題目標簽:Array
這道題目給了我們一個target, 要我們從array裏找到兩個數相加之和等於這個target。簡單粗暴search, 兩個for loop,遍歷array,每次的 用target 減去當前數字, 在剩下的array裏取找。
Java Solution:
Runtime beats 40.09%
完成日期:03/09/2017
關鍵詞:Array
關鍵點:Brute force search
1 public class Solution 2 { 3 public int[] twoSum(int[] nums, int target) 4{ 5 int [] res = new int[2]; 6 7 for(int i=0; i<nums.length; i++) 8 { 9 int m = target - nums[i];; 10 11 for(int j=i+1; j<nums.length; j++) 12 { 13 if(nums[j] == m) 14 { 15res[0] = i; 16 res[1] = j; 17 return res; 18 } 19 } 20 21 } 22 23 return res; 24 } 25 }
參考資料:N/A
LeetCode 算法題目列表 - LeetCode Algorithms Questions List
LeetCode 1. Two Sum (兩數之和)