排序和双指针,减小时间复杂度

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;
  }

猜你喜欢

转载自www.cnblogs.com/tqw1215/p/13388126.html