码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode算法题--刷题第一天

时间:2018-02-11 01:15:05      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:参考   imp   dice   targe   style   example   put   oid   round   

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算法题--刷题第一天

标签:参考   imp   dice   targe   style   example   put   oid   round   

原文地址:https://www.cnblogs.com/dwystyle/p/8440083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!