LeetCode1-Two Sum

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

题目:给定一数组,输出满足条件的数组下标,实现的思想比较简单,先实现排序,然后采用start、end下标遍历满足条件的下标。

/*
 * time:2016-7-25 22:08:24
 * location:home
 * */

import java.util.Arrays;

public class Solution {
	public static int[] twoSum(int[] nums, int target){

//		int[] res = new int[2];
//		res[0] = -1;
//		res[1] = -1;
//		
//		final HashMap<Integer, Integer> h = new HashMap<Integer,Integer>();
//		
//		for(int i = 0; i < nums.length; i++){
//			if(h.containsKey(target - nums[i])){
//				int index = h.get(target-nums[i])+1;
//				res[0] = Math.min(i+1, index);
//				res[1] = Math.max(i+1, index);
//			}
//			h.put(nums[i],i);
//		}
//		
//		return res;
		
		
//O(nlogn)
	int a = 0, b=0;
	int start = 0, end = nums.length-1;
	int [] nums2 = Arrays.copyOf(nums, nums.length);
	Arrays.sort(nums2);
	//find the nums,头尾指针
	while(start < end){
		int sum = nums2[start] + nums2[end];
		if(sum < target){
			start++;
		}
		else if(sum > target){
			end--;
		}
		else{
			a = nums2[start]; b = nums2[end];
			break;
		}
	}
	//find the index of the nums
	int[] res = new int[2];
	for(int i = 0; i < nums.length; i++){
		if(nums[i] == a){
			res[0] = i;
			break;
		}
	}
	
	if(a != b){ 
		for(int i =0; i < nums.length; i++){
			if(nums[i] == b){
				res[1] = i;
				break;
			}
		}
	} else {
		for(int i = 0; i < nums.length; i++){
			if(nums[i] ==b && i != res[0]){
				res[1] = i;
				break;
			}
		}
	}
	return res;
	
	}
	//test
	public static void main(String[] args){
		int[] nums = {3,2,2,7,7,8,11,15};
		int tagert = 9;
		
		
		int[] result = twoSum(nums,tagert);
		
		for(int i=0; i < result.length; i++){
			System.out.println("res[i]"+result[i]);
		}
		
	}
//	public int[] TwoSum(int[] nums, int target){
//		
//	}

}
代码参考leetcode discussion

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值