continuously moving the stone until leetcode 1040. II (sliding window)

Meaning of the questions:

A length of the infinite number of axes, the position of the i-th particle gravel stones [i]. If the location of a stone minimum / maximum, then the endpoint is called stone gravel.
 
Each turn, you can pick up a stone and move the endpoint to a location unoccupied, so that the stone is no longer an endpoint stone.
 
It is noteworthy that, if the stones like stones = [1,2,5] In this way, you will not be able to move stones endpoint is located at position 5, because whether it will be moved to any position (such as 0 or 3), the stones are still is the endpoint stones.
 
When you can not make any movement, that is, the position of these stones in a row, the game ends.
 
To make the game ends, the minimum and maximum number of moves you can perform are how much? An array of length 2 returns Answer: answer = [minimum_moves, maximum_moves] .
 
 
 
Example 1:
 
Input: [7,4,9]
Output: [1,2]
Explanation:
we can move one, 4 -> 8, the game ends.
Or, we can move twice 9 -> 5,4 -> 6, the game is over.
Example 2:
 
Input: [6,5,4,3,10]
Output: [2,3]
Explanation:
we can move 3 -> 8, followed by a 10 -> 7, the game ends.
Alternatively, we can move 3 -> 7, 4 -> 8, 5 -> 9, the game ends.
Note that we can not be 10 -> 2 such movements to end the game, because it is moving undesirable.
Example 3:
 
Input: [100,101,104,102,103]
Output: [0,0]

 

Ideas:

First, to clarify the specific operation, is essentially the number of axis points with minimum number of moves into a contiguous sequence period, due to the maximum number of moves may be obtained directly: each movement from outside to inside are all voids are moved once It can be the beginning of the most left to the far right or the far right of the gap to the far left, depending on which voids the longest, so the number is moving up: total void -min (leftmost gap, far right void); the minimum number of movements, the sliding window may be used, a window size of n is the length of the section, near the beginning of n is incremented until the length of the number j, then the number of movements of the window is not the point. Note that encountered a continuous window from outside points only when a two-step process.

 1 class Solution {
 2 public:
 3     vector<int> numMovesStonesII(vector<int>& stones) {
 4         int mi=0x3f3f3f3f,ma=0,n=stones.size();
 5         sort(stones.begin(),stones.end());
 6         ma=stones[n-1]-stones[0]-min(stones[n-1]-stones[n-2],stones[1]-stones[0])-n+2;
 7         for(int i=0,j=0;i<n;i++){
 8             while(stones[i]-stones[j]+1>n)j++;
 9             if(i-j==stones[i]-stones[j]&&n-(i-j+1)==1)mi=min(mi,2);
10             else mi=min(mi,n-(i-j+1));
11         }
12         vector<int>v;
13         v.push_back(mi); v.push_back(ma);
14         return v;
15     }
16 };
View Code

Guess you like

Origin www.cnblogs.com/ljy08163268/p/11735512.html