[LeetCode-Java]1.TwoSum

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.

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

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

解1:使用嵌套循环进行查询,时间复杂度O(n*n),运行时间72ms

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

        int[] result = null;
        //时间复杂度:O(n*n)
        for (int i = 0;i<nums.length-1;i++){
            for (int j=i+1;j<nums.length;j++){
                if (nums[i]+nums[j] == target){
                    result = new int[]{i,j};
                }
            }
        }

        return result;
    }

解2:利用map.containsKey方法,时间复杂度O(n) ,运行时间8ms

//利用map  8ms
    public static int[] twoSum2(int[] nums,int target){

        int[] result = null;

        HashMap<Integer,Integer> map = new HashMap<>();

        for (int i = 0;i < nums.length;i++){//O(n)
            if (map.containsKey(target - nums[i])){  //O(1)
                result = new int[]{map.get(target - nums[i]),i};
                break;
            }else {
                map.put(nums[i],i);
            }
        }

        return result;
    }

解3:使用类二分查找,时间复杂度O(n)+O(n*log(n))+O(n) ,运行时间7ms

//二分查找  7ms
    public static int[] twoSum3(int[] nums,int target){

        int[] result = null;

        int[] copyNums = Arrays.copyOf(nums,nums.length);//O(n)

        //排序  使用的是快速排序和优化的合并排序   n*log(n)
        Arrays.sort(nums);

        int lo = 0;
        int hi = nums.length-1;

        int m = 0;
        //O(n)
        while(lo<hi){
            m = nums[lo] + nums[hi];

            if (m>target){
                hi--;
            }else if (m<target){
                lo++;
            }else {
                //找到对应的两个值,此时需要找到二者原来的位置
                int index1 = 0;
                int index2 = 0;
                //记录  防止两个指数相等引起的错误
                boolean flag1 = false;
                boolean flag2 = false;

                for (int i=0;i<copyNums.length;i++){ //O(n)
                    if (copyNums[i] == nums[lo]  && !flag1){
                        index1 = i;
                        flag1 = true;
                    }else if (copyNums[i] == nums[hi] && !flag2){
                        index2 = i;
                        flag2 = true;
                    }
                }

                if (index1<index2) {
                    result = new int[]{index1, index2};
                }else {
                    result = new int[]{index2,index1};
                }

                break;
            }

        }

        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值