Two Sum

package leetcode.xuyi;
import org.junit.*;

import java.util.Arrays;
import java.util.HashMap;

/**
 * Created by ethan on 2015/5/2.
 */
public class No1TwoSum {
    // 思路1
    // 直接双重循环必然超时
    // 时间复杂度是O(n2)
//    public int[] twoSum(int[] nums, int target) {
//        int index1 = 0;
//        int index2 = 0;
//        boolean flag = false;
//        for (int i=0; i<nums.length-1; i++){
//            if (flag)
//                break;
//            int tmp = nums[i];
//            for (int j=i+1; j<nums.length; j++){
//                if(tmp + nums[j] == target) {
//                    index1 = i;
//                    index2 = j;
//                    flag = true;
//                }
//            }
//        }
//        return new int[]{index1+1, index2+1};
//    }

    // 思路2
    // 采用hashMap 其中key值放数值,value放index
    // 时间复杂度是O(n)
    public int[] twoSum1(int[] nums, int target){
        // 注意代码的健壮性,对于参数的requirement
        // 认为数组中的不存在重复的元素
        if (nums==null || nums.length<2) return null;
        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        for (int i=0; i<nums.length; i++){
            hashMap.put(nums[i], i);
        }
        int[] arr = null;
        for (int i=0; i<nums.length; i++){
            int num2 = target - nums[i];
            Integer index2 = hashMap.get(num2);
            // 注意可能找到自己
            if (index2!=null && index2!=i){
                arr = new int[]{i+1, index2.intValue()+1};
                break;
            }
        }
        return arr;
    }

    // 思路3
    // 排序(构造一个class{value,index}, 定义一个comparator), 两个指针一个指头,一个指尾, 不会重复扫描
    // 复杂度: O(nlogn)
    public int[] twoSum(int[] nums, int target){
        if (nums==null || nums.length<2) return null;
        // sort
        Arrays.sort(nums);
        // 寻找合适的index1, index2
        int start = 0;
        int end = nums.length-1;
        int[] arr = null;
        while(start < end){
            if (nums[start]+nums[end]==target){
                arr = new int[]{start+1, end+1};
                break;
            }else if(nums[start]+nums[end]<target){
                start++;
            }else{
                end++;
            }
        }
        return arr;
    }

    @Test
    public void test1(){
        int[] aa = twoSum(new int[]{2,7,11}, 9);
        System.out.println(aa[0]+" "+aa[1]);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值