Detailed explanation of the algorithm: Yang Hui's triangle | Merge two ordered arrays | Delete duplicates in the ordered arrays


Foreword: The topics shared this time are all from Likou.com. You can choose your own challenges. Detailed links:

118. Yang Hui Triangle – LeetCode

88. Merge two sorted arrays - LeetCode

26. Remove duplicates in ordered array - LeetCode

Table of contents

1. Yang Hui Triangle

Idea:

Complete code:

2. Merge two ordered arrays

Idea:

Complete code:

3. Remove duplicates in an ordered array

Idea:

Complete code:


1. Yang Hui Triangle

Title:Given a non-negative integer numRows, generate the first part of "Yang Hui's triangle" a> numRows rows (1 <= numRows <= 30)

Note:In "Yang Hui's Triangle", each number is the sum of the numbers on its upper left and upper right

Example one:

Import: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[ 1,4,6,4,1]]

 Example 2:

Import: numRows = 1
Output: [[1]]

Idea:

We can change the direction of Yang Hui's triangle and change it to a ladder type, which may be more suitable for our understanding. For such ladder type data, we will naturally think of a two-dimensional array. So can Yang Hui's triangle be used as a two-dimensional array? What about array implementation?

For each row of data, the first and last ones are both 1, and the remaining data are the data at the same position in the previous row plus the previous data, which means we need to use it when implementing the data in each row. data from the previous row. In order to complete the above process more efficiently, we can use a two-dimensional sequence table instead of a two-dimensional array to operate.

After deciding to use a two-dimensional sequence table, we need to define a general sequence table to store the sequence table corresponding to each row, using the outer layerfor loop Determine how many rows there are, and use the inner layerfor loop to determine the elements of each row. The above determines the general framework of this question.

There are a few details to note:

Summary observation of Yang Hui's triangle, all1 positions are at the beginning and end of each line, the beginning is very simple and the inner layer “1” , we will add elements to the row sequence table (j == 0 || j == i) is equal, in summary, when the loop variable j variablefor loopand inner layer i for loop; is the starting position, and the For the last element, if we carefully observe its coordinates, we will find that its number of rows and columns are equal, which is the loop variable of the outer j=0 for loop

For data other than 1, we need to access the data in the previous row through .get( i-1) can get the sequence table of the previous row. After getting the sequence table of the previous row, get the j of this row respectively. to add this value to the sequence table of this row .add position elements, and then add them together. The result of the addition is the value we want, and finally Just use j-1 position and

Complete code:

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> ret = new ArrayList<>();
        for (int i = 0; i < numRows; i++) {
            //新定义一行
            List<Integer> row = new ArrayList<>();
            for (int j = 0; j <= i; j++) {
                if (j == 0 || j == i) {
                    row.add(1);
                }else {
                    //添加上一行的数据(上一行的j-1和j位置)
                    row.add(ret.get(i-1).get(j-1) + ret.get(i-1).get(j));
                }
            }
            //每一次将新的一行加入总的二维顺序表中
            ret.add(row);
        }
        return ret;
    }
}

2. Merge two ordered arrays

Title: Give you two integer arrays arranged in non-decreasing order  nums1  and nums2, and two integers m and n respectively represent  . Please merge  into  so that the merged array is also  Arrange in descending order . nums1nums2 nums2 nums1

Note:Ultimately, the merged array should not be returned by the function, but stored in the array nums1 . In order to cope with this situation, the initial length of nums1 is m + n, where the first m elements represent the elements that should be merged, and the last < /span>  .  is  and should be ignored. The length of n elements are 0nums2n

Example one:

Import:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Exit:[1,2,2,3,5,6]
Solution:Demand sum [1,2,3] sum [2,5,6]. 
The result is [1,2,2, 3,5,6] 

Example two:

Import:nums1 = [1], m = 1, nums2 = [], n = 0
Exit:[1]
Solution:Demand sum [1] sum []. 
The result is [1] 

 Example three:

Input:nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays that need to be merged are [] and [1]. 
The combined result is [1]

Idea:

For an array, we want to merge it into a brand new array. We can use two pointers to point to the two arrays respectively, and then compare the two pointers with the smaller value, and put the smaller value into the new array, and pointer moves backward

There are a total of 4 situations for inserting data, and we will deal with them respectively:

  1. nums1 The data of is less than the data of  nums2 : Put the data of nums1 into the new array, and after the pointer pA move
  2. nums1 The data of is greater than the data of  nums2 : Put the data of nums2 into the new array, and after the pointer pB move
  3. nums1 The data of has been excluded, but nums2 still has elements: put the elements of nums2 into the new array, and move the pointer pB back
  4.  nums2 The data of has been eliminated, but nums1 still has elements: put the elements of nums1 into the new array, and move the pointer pA back

We use awhile loop to include all situation traversals, and then each judgment puts a piece of data into a new array through a temporary variable , in order to satisfy the question requirements, the final result is overwritten into array 1

Complete code:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int pA = 0;
        int pB = 0;
        int cur = 0;
        int[] sordNum = new int[m + n];
        while (pA < m || pB < n) {
            if (pA == m) {//nums1已满,放入nums2
                cur = nums2[pB++];
            } else if (pB == n) {//nums2已满,放入nums1
                cur = nums1[pA++];
            } else if (nums1[pA] < nums2[pB]) {//nums1的数据小于nums2
                cur = nums1[pA++];
            } else {//nums1的数据大于等于nums2
                cur = nums2[pB++];
            }
            sordNum[pA + pB - 1] = cur;
        }
        for (int j = 0; j != m + n; ++j) {
            nums1[j] = sordNum[j];
        }
    }
}

3. Remove duplicates in an ordered array

Title: Give you an array non-strictly increasing arrangement nums , please  delete repeated elements in situ  so that each element  appears only once .  . Then return the number of unique elements in consistent of the elements should remain relative order , returns the new length of the array after deletion. The nums

Example one:

Import:nums = [1,1,2]
Output:2, nums = [1,2,_]

Example two:

Import:nums = [0,0,1,1,1,2,2,3,3,4]
Output:5, nums = [0,1,2,3,4]

Idea:

For thedeletion here, we can make clever use of it. Specifically, we can put the non-repeating elements in front of the array, and then We only return this part of non-repeating elements, thus achieving the goal of deletion in disguise

Complete code:

class Solution {
    public int removeDuplicates(int[] nums) {
        //快慢指针
        int left = 0;
        int right = 1;
        while(right < nums.length){
            if(nums[left] != nums[right]){
                left++;
                nums[left] = nums[right];
            }
            right++;
        }
        return left + 1;
    }
}



  That’s it for this sharing. I hope my sharing can be helpful to you. I also welcome everyone’s support. Your likes are the biggest motivation for bloggers to update! If you have different opinions, you are welcome to actively discuss and exchange in the comment area, let us learn and make progress together! If you have relevant questions, you can also send a private message to the blogger. The comment area and private messages will be carefully checked. See you next time

Guess you like

Origin blog.csdn.net/m0_69519887/article/details/134805409