[Leetcode / min] found two k nearest element (sliding window bipartite +)

Problem Description:

Given a good array of two integers sort kand xfind the closest from the array x(the number of difference between the two smallest) knumber. If the result returned must be properly arranged in ascending order. If there are two numbers with a xdifference, as the number of small value preferences.

Example 1:

Input: [1,2,3,4,5], K =. 4, X =. 3
 Output: [1,2,3,4]

 

Example 2:

Input: [1,2,3,4,5], K =. 4, X = -1
 Output: [1,2,3,4]

 

Description:

  1. The k value is positive, and is always smaller than the length of a given array is sorted.
  2. Array is not empty, and a length of no more than 104
  3. The absolute value of each element in the array is not more than 104 x

The basic idea:

Using binary find the nearest element of interval around the pointer, and finally adding the result to traverse the result set interval.

AC Code:

class Solution {
public:
  vector<int> findClosestElements(vector<int>& arr, int k, int x) {
	if(arr.size() == 1){
        return arr;
    }
    int beg = 0;
    int end = arr.size() - k;
    while(beg < end){
        int mid = beg + (end - beg)/2;
        if(abs(arr[mid] - x) > abs(arr[mid + k] -x)){
            beg = mid + 1;
        }
        else{
            end = mid;
        }
    }
      
	return vector<int>{arr.begin()+beg, arr.begin()+beg+k};
}
};

Daniel's ideas:

Since k is a constant element of the k-th element bound together.

So we thought of a sliding window.

Window far left and the far right elements are in line with the requirements of the last two elements, we move the window, only need to determine the edge position on the line.

There is also used a dichotomous thinking, think about actually correct.

class Solution {
public:
  vector<int> findClosestElements(vector<int>& arr, int k, int x) {
	if(arr.size() == 1){
        return arr;
    }
    int beg = 0;
    int end = arr.size() - k;
    while(beg < end){
        int mid = beg + (end - beg)/2;
        if(abs(arr[mid] - x) > abs(arr[mid + k] -x)){
            beg = mid + 1;
        }
        else{
            end = mid;
        }
    }
      
	return vector<int>{arr.begin()+beg, arr.begin()+beg+k};
}
};

Other experience:

  1.  3 using the binary template must pay attention to mid parked in the left or the right situation, find ways to solve it . (Now I do not have a better way to see the result, if it eventually stopped on the left, modify mid; right = mid if parked on the right, to meet the requirements - 1)
  2.  Sometimes we will be an interval as a unit half, in fact, this is the dichotomy + sliding window .
发布了137 篇原创文章 · 获赞 19 · 访问量 1万+

Guess you like

Origin blog.csdn.net/qq_43338695/article/details/102775608