Algorithmic customs clearance village - the magical use of double pointers

1. The topic of odd and even movement of elements

1.1 Sort arrays by odd-even

Sort an array by odd-even Given
you an integer array nums, move all even elements in nums to the front of the array, followed by all odd elements.
Returns any array that satisfies this condition as the answer.

1.1 Left and right pointer

The first reaction is that you only need to place even numbers on the left and odd numbers on the right. You can use two pointers, one on the far left and one on the far right, and move to the middle at the same time. You need to judge whether the left element is an even number. If so Odd number, and the right element is an even number, the position is exchanged, but if the left element is even, then the left self-increment is ok, but if the right element is odd, it is satisfied, and the right self-decreases.

public int[] sortArrayByParity(int[] nums) {
    
    
        int left =0;
        int right = nums.length -1;
        while(left<right){
    
    
            if(left<right && nums[left] % 2==0){
    
    
                left++;
            }
            if(left<right && nums[right]%2!=0){
    
    
                right--;
            }
            if(nums[left] %2!=0 && nums[right] %2==0 ){
    
    
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right]=temp;
                left++;
                right--;
            }
        }
        return nums;
    }

Time complexity: O(n)
Space complexity: O(1)

2 Array rotation problem

2.1 Rotation array

Rotate an Array
Given an integer array nums, rotate the elements in the array k positions to the right, where k is a non-negative number.

2.1.1 Inversion

The first idea is to reverse the array one by one, inserting the last element to the front in turn. But the advantages of this situation are complicated, and there are many things to consider. So inversion is used, first all elements are inverted, and then the elements before the k element are inverted, and the elements after k are also inverted. Here you need to convert k into a subscript, that is, the element at position k-1.
insert image description here

 public void rotate(int[] nums, int k) {
    
    
        k = k% nums.length;
        reverse(nums,0,nums.length-1);
        reverse(nums,0,k-1);
        reverse(nums,k,nums.length-1);
    }

    public void reverse(int [] nums,int start,int end){
    
    
        while(start <end){
    
    
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start+=1;
            end-=1;
        }
    }

Time complexity: O(N) The first inversion is O(N), the second time is O(k), and the third time is O(Nk) Space
complexity: O(1)

3. Interval Topics for Arrays

3.1 Summary interval

Summarizing Intervals
Given an ordered integer array nums with no repeating elements.
Returns the smallest ordered list of interval ranges that exactly cover all the numbers in the array. That is, each element of nums is covered by exactly some interval range, and there is no number x that falls within a certain range but does not belong to nums.
Each range [a,b] in the list should be output in the following format:
"a->b" if a != b
"a" if a == b

3.1.1 Fast and slow pointer

Let the fast pointer go all the way. When the element behind the fast pointer is not continuous with the current element, return the string of the start element and the fast pointer element, and then the slow pointer at this time will jump to the last element position of the fast pointer. as the next initial position. In the middle, it is necessary to judge whether the current speed pointer is at the same position, and if so, it means that there is only one element.
insert image description here

public List<String> summaryRanges(int[] nums) {
    
    
        int slow = 0;
        List<String> list = new ArrayList<>();
        for(int fast =0;fast<nums.length;fast++){
    
    
            //fast 向后遍历,不满足条件nums[fast]+1=nums[fast+1],就是不连续的
          if(fast+1 ==nums.length || nums[fast] +1 !=nums[fast+1]){
    
    
              StringBuilder sb = new StringBuilder();
              // 记录下开始元素
              sb.append(nums[slow]);
              if(slow!=fast){
    
    
                  // 记录结束元素
                  sb.append("->").append(nums[fast]);
              }
              list.add(sb.toString());
              // 下一个区间起始位置
              slow =fast+1;
          }
        }
        return list;
    }

Time complexity: O(N)
Space complexity: O(1)

3.2 Missing spaces

Link 163 requires membership.
It is basically the same as 3.1, but now it is to get the missing space
For example: nums[0,1,3,50,75] ,lower=0,upper=99
The result is: ["2", "4->49", "51->74", "76->99"]

3.2.1 Fast and slow pointer

First of all, this question is the same, let the fast pointer move until it is discontinuous, but now there is no need for the slow pointer, just record the space output between the fast pointer element and the next position element, but you need to judge the current element Whether it exceeds the range of lower and upper.

  public static List<String> findNonContiguousSpaces(int[] nums, int lower, int upper) {
    
    
        List<String> list = new ArrayList<>();
        int n = nums.length;

        if (nums[0] > lower) {
    
    
            int start = lower;
            int end = nums[0] - 1;
            list.add(start + "->" + end);
        }


        for (int fast = 1; fast < n - 1; fast++) {
    
    
            int prev = nums[fast] + 1;
            int cur = nums[fast + 1] - 1;
            list.add(prev + "->" + cur);
        }

        if (nums[n - 1] < upper) {
    
    
            int end = upper;
            int start = nums[n - 1] - 1;
            list.add(start + "->" + end);
        }

        return list;
    }

Time complexity: O(n)
Space complexity: O(1)

4. Replace spaces with strings

4.1 Replace spaces

Replace spaces
Please implement a function to replace each space in the string s with "%20".

4.1.1 String interception

Create a new String, save each character in the string using char, if the character is empty, splice "%20", if not, splice directly.

public String replaceSpace(String s) {
    
    
        String rep = "";
        for(int i=0;i<s.length();i++){
    
    
            char c = s.charAt(i);
            if(c == ' '){
    
    
                rep+="%20";
            }else{
    
    
                rep+=c;
            }
        }
        return rep;
    }

Time complexity: O(N^2) is mainly to traverse the string and splice the string again.
insert image description here
Obviously, the time and space efficiency is relatively low.

4.1.2 Fast and slow pointer

First calculate how many spaces there are, add a %20, occupying three bytes, and one space occupies one byte, all the extra length is 2 bytes, a total of 2*n bytes extra, Then expand the length of the stringbuffer, place the slow pointer at the end of the new string, and the fast pointer at the end of the original string. When the fast pointer encounters a space, you need to use three characters to replace a space, and then slow moves three positions, and fast moves one position until fast reaches the starting position.

 public String replaceSpace(String s) {
    
    
        StringBuffer str= new StringBuffer(s);
        if(str ==null) return null;
        int blankCount =0;
        int len = str.length();
        for(int i=0;i<len;i++){
    
    
            if(str.charAt(i) == ' '){
    
    
                blankCount++;
            }
        }

        int newLength = len+2*blankCount;
        str.setLength(newLength);
        int slow = newLength-1;
        int fast = len-1;

        while(fast>=0 && slow!=fast){
    
    
            char c = str.charAt(fast);
            if(c==' '){
    
    
                fast--;
                str.setCharAt(slow--,'0');
                str.setCharAt(slow--,'2');
                str.setCharAt(slow--,'%');
            }else{
    
    
                str.setCharAt(slow,c);
                fast--;
                slow--;
            }
        }
        return str.toString();
        }

insert image description here
It can be seen that the time is still very fast.
Time complexity: O(n), first traverse the string once, find the number of spaces, and then expand the new string

Guess you like

Origin blog.csdn.net/qq_52843958/article/details/131939472