zoukankan      html  css  js  c++  java
  • 排序和双指针,减小时间复杂度

    1. 最接近的三数之和
    给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案.
     
    解题思路:(总时间复杂度为O(nlogn) + O(n2))
      1.对数组进行升序排序,时间复杂度为O(nlogn)
      2.三数之和sum = nums[i] + nums[left] + nums[right]
      3.for循环固定nums[i],时间复杂度为O(n)
      4.left指针向右递增,nums[left]值向右递增,right指针向左递减,nums[right]值向左递减
      5.判断nums和target大小移动左右两个指针,找到最接近target的nums,时间复杂度为O(n)
     
    public int threeSumClosest(int[] nums, int target) {
          int n = nums.length;
          Arrays.sort(nums);
          int threeAns = nums[0] + nums[1] + nums[2];
          for (int i = 0; i < n; i++) {
              int left = i + 1; int right = n - 1;
              while(left < right){
                  int sum = nums[i] + nums[left] + nums[right];
                  if (Math.abs(threeAns - target) > Math.abs(sum - target)){
                      threeAns = sum;
                  }
                  if(sum > target){
                      right--;
                  }else if(sum < target){
                      left++;
                  }else{
                      return threeAns;
                  }
              }
          }
          return threeAns;
      }
  • 相关阅读:
    PKU 3984 迷宫问题
    九度 1341 艾薇儿的演唱会
    九度 1335
    SDUT 1198 鞍点计算
    POJ 1363 Rails
    SDUT 1570 C旅行
    HDU 1042 N!
    SDUT 1568 俄罗斯方块
    HDU 1257 最少拦截系统
    POJ 3750 小孩报数问题
  • 原文地址:https://www.cnblogs.com/tqw1215/p/13388126.html
Copyright © 2011-2022 走看看