1. 程式人生 > >LeetCode算法題--刷題第一天

LeetCode算法題--刷題第一天

ive strong targe 方案 imp string color not ces

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]

代碼實現:(參考)

 1     import java.util.HashMap;  
 2     import java.util.Map;  
 3       
 4     public class Solution {  
 5         public static int[] twoSum(int[] nums, int target) {  
 6             int[] result = new int[2];  
 7             Map<Integer,Integer> map = new HashMap();  
 8
for(int i=0; i<nums.length; i++){ 9 if(map.containsKey(target - nums[i])){ 10 if(map.get(target - nums[i]) > i){ 11 result[0] = i; 12 result[1] = map.get(target - nums[i]); 13 }else
{ 14 result[1] = i; 15 result[0] = map.get(target - nums[i]); 16 } 17 return result; 18 } 19 map.put(nums[i], i); 20 } 21 return result; 22 } 23 24 public static void main(String[] args) { 25 int[] nums = {3,2,4}; 26 int target = 6; 27 int[] result = new int[2]; 28 result = twoSum(nums,target); 29 System.out.println(result[0] + " " + result[1]); 30 } 31 }

LeetCode算法題--刷題第一天