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

LeetCode 001_Two Sum Java

时间:2015-05-29 23:18:15      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:leetcode   hashmap   java   

public class Solution {
	    public int[] twoSum(int[] nums, int target) {
	        int temp;
	        boolean flag = false;
	        int[] index = new int[2];
	        for(int i = 0; i < nums.length; i++){
	            temp = target - nums[i];
	            for(int j = 0; j < nums.length; j++){
	            	if(i == j) continue;
	                if(temp == nums[j]){
	                    index[1] = j+1;
	                    flag = true;
	                    break;
	                }
	            }
	            if(flag){
	                index[0] = i+1;
	                break;   
	            }
	        }
	        return index;
	    }
	  
思路二: 
把数组的值作为map的key, 由于满足 nums[i] + nums[j] = target ,故必存在key值满足nums的元素
	    public int[] twoSum2(int[] nums, int target) {    
	        int[] index=new int[2];  
	        HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();  
	          
	        for(int i = 0; i<nums.length; i++)  
	        {  
	            if(hm.containsKey(target - nums[i]))  
	            {  
	                index[1] = i+1;  
	                index[0] = hm.get(target-nums[i])+1;     
	                return index;     
	            }else  
	            {  
	                 hm.put(nums[i],i);  
	            }  
	        }  
	        return index;    
	    }  
	}

LeetCode 001_Two Sum Java

标签:leetcode   hashmap   java   

原文地址:http://blog.csdn.net/xu758142858/article/details/46238979

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