A bit difficult, a few algorithms interview questions and "sliding window" relevant

Preface science: What is the sliding window algorithm

The slide comprises a sliding window problem, which is a sub-list on a large array of operation, the array is a collection of the underlying elements.

Suppose the array [ABCDEFGH], a size of 3 sliding window to slide thereon, there are:

[a b c]
  [b c d]
    [c d e]
      [d e f]
        [e f g]
          [f g h]

Under normal circumstances it is to use this window in an array of legal sections to slide inside, while dynamically record some useful data, in many cases, can greatly improve the efficiency of the algorithm.

1. The sliding window maximum

The title comes from the first LeetCode No. 239 issue: sliding window maximum. Difficulty of the subject is Hard, by the current rate of 40.5%.

Title Description

Given an array the nums , have a size of k rightmost sliding window moves from the leftmost array to array. You can only see in a sliding window k numbers in. A time sliding window moves to the right one.

Returns the maximum sliding window.

Example:

输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7] 
解释: 

  滑动窗口的位置                最大值
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Analytical title

The use of a double-ended queue , in the array of storage elements position in the queue, and maintain strictly decreasing queues ,, it is to say to maintain the team's first element is the greatest , when traversing to a new element, if there is more than the current queue small elements, it will be removed queues to ensure decreasing queue. When the difference is greater than a queue element position k, the first element of the team will be removed.

Added: What is the double-ended queue (Dqueue)

Deque the meaning of "double ended queue", i.e. deque which has a data structure and properties of the queue stack. As the name implies, it is a front end and the rear end support insert and delete operations queue.

Deque inherited from the Queue (queue), its direct implementation have ArrayDeque, LinkedList and so on.

Animation description

Animation description Made by Jun Chen

Code

class Solution {
   public int[] maxSlidingWindow(int[] nums, int k) {
        //有点坑,题目里都说了数组不为空,且 k > 0。但是看了一下,测试用例里面还是有nums = [], k = 0,所以只好加上这个判断
        if (nums == null || nums.length < k || k == 0) return new int[0];
        int[] res = new int[nums.length - k + 1];
        //双端队列
        Deque<Integer> deque = new LinkedList<>();
        for (int i = 0; i < nums.length; i++) {
            //在尾部添加元素,并保证左边元素都比尾部大
            while (!deque.isEmpty() && nums[deque.getLast()] < nums[i]) {
                deque.removeLast();
            }
            deque.addLast(i);
            //在头部移除元素
            if (deque.getFirst() == i - k) {
                deque.removeFirst();
            }
            //输出结果
            if (i >= k - 1) {
                res[i - k + 1] = nums[deque.getFirst()];
            }
        }
        return res;
     }
}

2. No repetition character longest substring

The title comes from LeetCode first 3 questions: no repeat of the longest character string. Title of difficulty Medium, by the current rate of 29.0%.

Title Description

Given a string, you find out which does not contain a repeated character longest substring length.

Example 1:

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

Analytical title

Establish a 256-bit integer array freg size, to establish the mapping between the character and appearance of its location.

Maintains a sliding window are no repeating characters in the window, as far as possible to expand the size of the window, the window kept sliding to the right.

  • (1) If the current traverse to the character never appeared, then direct the expansion of the right border;
  • (2) If the current traverse to the character appeared, the narrow window (left index moves to the right), then traverse to continue to observe the current character;
  • (3) repeat (1) (2), the index can not be moved again until the left;
  • (4) maintains a result res, each with a window size appeared to update the results res, and finally return res get results.

Animation description

Animation description

Code

// 滑动窗口
// 时间复杂度: O(len(s))
// 空间复杂度: O(len(charset))
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int freq[256] = {0};
        int l = 0, r = -1; //滑动窗口为s[l...r]
        int res = 0;
        // 整个循环从 l == 0; r == -1 这个空窗口开始
        // 到l == s.size(); r == s.size()-1 这个空窗口截止
        // 在每次循环里逐渐改变窗口, 维护freq, 并记录当前窗口中是否找到了一个新的最优值
        while(l < s.size()){
            if(r + 1 < s.size() && freq[s[r+1]] == 0){
                r++;
                freq[s[r]]++;
            }else {   //r已经到头 || freq[s[r+1]] == 1
                freq[s[l]]--;
                l++;
            }
            res = max(res, r-l+1);
        }
        return res;
    }
};

3. The presence of repetitive elements II

The title comes from LeetCode's first 219 issues: the presence of repetitive elements II. Item difficulty is Easy, the current pass rate of 33.9%.

Title Description

Given an integer array and an integer K , if there are two different indexes in the array is determined i and j , such that the nums [i] = the nums [j] , and i and j maximum absolute value of the difference K .

Example 1:

输入: nums = [1,2,3,1], k = 3
输出: true

Example 2:

输入: nums = [1,0,1,1], k = 1
输出: true

Example 3:

输入: nums = [1,2,3,1,2,3], k = 2
输出: false

Analytical title

Use a sliding window with a lookup table to resolve.

  • Provided lookup table record, for holding the insertion element each pass, recordthe maximum length ofk
  • Iterate nums, iterate every time in recordto find out if there is the same element, if it returns true, traversing the end
  • If the traversal recordis not found, then inserted into the elements recordof, and then see recordif the length isk + 1
  • If at this time recordif the length of k + 1, the deletion of recordthe element, the element isnums[i - k]
  • If you traverse the full array numsis not found is returnedfalse

Animation description

Animation description

Code

// 时间复杂度: O(n)
// 空间复杂度: O(k)
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if(nums.size() <= 1)  return false;
        if(k <= 0)  return false;
        unordered_set<int> record;
        for(int i = 0 ; i < nums.size() ; i ++){
            if(record.find(nums[i]) != record.end()){
                return true;
            }
            record.insert(nums[i]);
            // 保持record中最多有k个元素
            // 因为在下一次循环中会添加一个新元素,使得总共考虑k+1个元素
            if(record.size() == k + 1){
                record.erase(nums[i - k]);
            }
        }
        return false;
    }
};

4. The length of the smallest sub-array

The title comes from the first 209 LeetCode problems: the minimum length of the subarray. Title of difficulty Medium, now by 37.7%.

Title Description

Given a containing n positive integers array and a positive integer s, identify the array and meet ≥ s minimum length of a continuous subarray . If successive sub-array qualifying does not exist, 0 is returned.

Example:

输入: s = 7, nums = [2,3,1,2,4,3]
输出: 2
解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。

Analytical title

Define two pointers left and right, respectively, is recorded around the boundary position subarray.

  • (1) to the right so that the right, until the sub-arrays and greater than or equal to a given value reaches right end of the array;
  • (2) update the shortest distance, the left as the right one, sum minus the value removed;
  • (3) repeat (1) (2) step, until reaching the right end, left and reach the critical position

Animation description

Sliding window length is set to 0, the leftmost axes.

1. R starts sliding window moves right until the interval meets a given condition, i.e. greater than 7 and, in this case the third element 2 is stopped, the optimum length of the current 4

figure 1

2. The left end of the sliding window L begins to move, shrink the size of the sliding window, a stop on the first element 3, and this time interval is 6, so that the section and do not satisfy the given condition (not more than 7 at this time)

Picture 2

R 3 sliding window continues to move right, the fourth element 4 is stopped, and the bit 10 at this time, but is still the optimal length of 4

Picture 3

Code

// 滑动窗口的思路
// 时间复杂度: O(n)
// 空间复杂度: O(1)
class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int l= 0,r = -1;    // nums[l...r]为我们的滑动窗口
        int sum = 0;
        int result = nums.length + 1;
        while (l < nums.length){ // 窗口的左边界在数组范围内,则循环继续

            if( r+1 <nums.length && sum < s){
                r++;
                sum += nums[r];
            }else { // r已经到头 或者 sum >= s
                sum -= nums[l];
                l++;
            }

            if(sum >= s){
                result = (r-l+1) < result ? (r-l+1) : result ;
            }
        }
        if(result==nums.length+1){
            return 0;
        }
        return result;
    }
}

❤️ reading three things:

If you find this content you quite inspiring, I want to invite you to help me busy three:

  • Thumbs up, so that more people can see this content (collection point no praise, bullying -_-)
  • Watch me and columns, so that we become a long-term relationship
  • Public concern number "five minutes learning algorithm", the first time to read the latest articles algorithm, public No. 1024 reply background give you 50 algorithm programming books.

Guess you like

Origin www.cnblogs.com/fivestudy/p/11422923.html