【Lanqiao Cup training】【Lip button training】【Elementary Algorithm——Array】


1. Delete duplicates in a sorted array (simple)

topic:

Given an ordered array nums, please delete repeated elements in place so that each element appears only once , and return the new length of the deleted array.

Don't use extra array space, you have to modify the input array in-place and do so using O(1) extra space.

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: The function should return a new length of 2, and the first two elements of the original array nums are modified to 1, 2. Elements beyond the new length in the array do not need to be considered.

Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4]
Explanation: The function should return the new length 5, and the first five elements of the original array nums are modified to 0, 1, 2, 3, 4. Elements beyond the new length in the array do not need to be considered.

Source: LeetCode
Link: https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array

analyze:

Because the title requires modifying the array in place, and the data is in order, we can judge whether a certain number is the same as the number between its neighbors, and can remove duplicate numbers, so we can use the fast and slow pointers to solve the problem.
First define a slow pointer j and a fast pointer i. i traverses the entire array starting from subscript 1, and j starts from subscript 0. When nums[i] != nums[j], j is incremented by one.
After i traverses the array, j + 1 is the length of the final array.

code:

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        n = len(nums)
        if n <= 1:
            return n
        j = 0
        for i in range(1,n):
            if nums[i] != nums[j]:
                j += 1
                nums[j] = nums[i]
        nums = nums[:j + 1]
        return j + 1

2. The best time to buy and sell stocks (medium)

topic:

Given an array prices, where prices[i] is the price of a given stock on day i.

Design an algorithm to calculate the maximum profit you can make. You can complete as many trades as possible (buy and sell a stock multiple times).

Note: You cannot participate in multiple transactions at the same time (you must sell the previous stock before buying again).

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (stock price = 1), sell on day 3 (stock price = 5) Out, this transaction can gain profit = 5-1 = 4.
Then, buy on the 4th day (stock price = 3) and sell on the 5th day (stock price = 6), this transaction can make a profit = 6-3 = 3.

Example 2:

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (stock price = 1), sell on day 5 (stock price = 5), This transaction can make a profit = 5-1 = 4.
Note that you cannot buy shares on Day 1 and Day 2 back-to-back and sell them later. Because this is involved in multiple transactions at the same time, you must sell the previous shares before buying again.

Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no trades are completed, so the maximum profit is 0.

Source: LeetCode
Link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii

analyze:

There are many solutions to this question, including dynamic programming and greedy. I chose a relatively simple greedy algorithm. That is, when the stock price of the day is higher than that of the next day, we will buy it and sell it the next day. No matter how big the profit is, we will buy it as long as there is a profit. For example: prices = [7,1,3,2,6,8],
first day: 7<1 do not buy;
second day: 1<3 buy and sell on the second day, profit: 2;
third day : 3>2, do not buy;
fourth day: 2<6, buy the next day sell, profit: 4;
fifth day: 6<8, buy the next day sell, profit: 2;
total profit For: 2+4+2=8
code:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        get = 0 #利润
        for i in range(len(prices) - 1):
            n = prices[i + 1] - prices[i] 
            if n > 0:
                get += n
        return get

3. Rotate array (medium)

Question:
Given an array, rotate the elements in the array k positions to the right, where k is a non-negative number.

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
Turn right 1 step: [7 ,1,2,3,4,5,6]
Turn right 2 steps: [6,7,1,2,3,4,5]
Turn right 3 steps: [5,6,7,1,2 ,3,4]

Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
Turn right 1 step: [99,-1,-100,3 ]
Turn right 2 steps: [3,99,-1,-100]

Source: LeetCode
Link: https://leetcode-cn.com/problems/rotate-array

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
Turn right 1 step: [7 ,1,2,3,4,5,6]
Turn right 2 steps: [6,7,1,2,3,4,5]
Turn right 3 steps: [5,6,7,1,2 ,3,4]

Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
Turn right 1 step: [99,-1,-100,3 ]
Turn right 2 steps: [3,99,-1,-100]

Source: LeetCode
Link: https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2skh7/

analyze:

The topic is that the array elements rotate k positions to the right, which is understood as the last k elements of the array are moved to the front. In this way, we can easily do it with the slice operation in Python. If you don't know the slice operation yet, you can learn it first.

code:

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        #当轮转次数大于数组长度时,我们对它取余,我当时写了个循环,但是更好的是直接取余
        while k > len(nums): 
            k -= len(nums)
        if k != 0:
            n = len(nums) - k
            a = nums[n:] #原数组的后k个位置的元素,现在做头
            b = nums[:n] #原数组的头,现在做尾
            for i in range(n):
                a.append(b[i])  #将尾元素添加到a的后面
            for i in range(len(nums)):
                nums[i] = a[i]

4. There are repeated elements (simple)

topic:

You are given an integer array nums. Returns true if any value occurs at least twice in the array; returns false if every element in the array is different.

Example 1:

Input: nums = [1,2,3,1]
Output: true

Example 2:

input: nums = [1,2,3,4]
output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Source: LeetCode
Link: https://leetcode-cn.com/problems/contains-duplicate

analyze:

There are many solutions to this problem.
After sorting, we can determine whether there are identical numbers in adjacent positions to determine whether there are duplicate numbers; we
can also define an empty array, traverse nums and add the elements one by one to the empty array, if a certain number is added, it is found that the number already exists If it is an empty array, it means that the number is repeated;
of course, it is easier to directly call the function set() that comes with Python to deduplicate the array. Then judge whether the length is the same as the length of the original array, and then it can be judged whether there are duplicate numbers.

code:

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(nums) != len(set(nums))

5. Numbers that appear only once (simple)

Question:
Given a non-empty array of integers, each element appears twice except for a certain element that appears only once. Find the element that appears only once.

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

Source: LeetCode
Link: https://leetcode-cn.com/problems/single-number

analyze:

The first few questions are to judge whether there are repeated numbers, this question has become to find the number of non-repeated numbers, and the idea is roughly the same.
We can sort the array, and then traverse the array to find out that an element is different from its adjacent number, then that number is the number that appears only once.

code:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        nums.sort() #原地排序
        if len(nums) == 1:
            return nums[0]
        for i in range(len(nums)):
            if i == 0: #首
                if nums[i] != nums[i + 1]:
                    return nums[i]
            elif i == len(nums) - 1: #尾
                if nums[i] != nums[i - 1]:
                    return nums[i]
            else: #中间元素
                if nums[i] != nums[i - 1] and nums[i] != nums[i + 1]:
                    return nums[i]

Six, the intersection of two arrays (simple)

topic:

Given you two integer arrays nums1 and nums2, please return the intersection of the two arrays as an array. The number of occurrences of each element in the returned result should be consistent with the number of occurrences of the element in both arrays (if the number of occurrences is inconsistent, consider taking a smaller value). The order of the output results can be ignored.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Source: LeetCode
Link: https://leetcode-cn.com/problems/intersection-of-two-arrays-ii

analyze:

This question needs to find the intersection of two arrays, and the number of elements appearing in the intersection must be the same as the original two arrays. If the number of occurrences of the two arrays is different, take the smaller one. At the beginning, my idea was to traverse the short array elements in the two arrays to determine whether the elements in them exist in the long array, so that the same elements can be found. But the problem of the number of occurrences of such elements cannot be easily solved.
Because it is mentioned in the title that the position of the element can be changed, we can sort the two arrays, and then use the fast and slow pointers to solve this problem. First define an empty array nums, determine the length of the two arrays, and then sort the two arrays. Use i and j to traverse the two arrays respectively. When nums1[i] == nums2[j], nums1[i] can be put into the defined empty array, and finally the short data traversal ends, and nums is the final result.

code:

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        l1 = len(nums1)
        l2 = len(nums2)
        nums = []
        nums1.sort()
        nums2.sort()
        j,i = 0,0
        if l1 < l2:
            while i < l1:
                if nums1[i] == nums2[j]:
                    nums.append(nums1[i])
                    j += 1
                    i += 1
                    if j == l2:
                        return nums
                elif nums1[i] > nums2[j]:
                    j += 1
                    if j == l2:
                        return nums
                else:
                    i += 1
            return nums
        else:
            while i < l2:
                if nums2[i] == nums1[j]:
                    nums.append(nums2[i])
                    j += 1
                    i += 1
                    if j == l1:
                        return nums
                elif nums2[i] > nums1[j]:
                    j += 1
                    if j == l1:
                        return nums
                else:
                    i += 1
            return nums

Seven, add one (simple)

topic:

Given a non-negative integer represented by a non-empty array of integers, add one to the number.

The highest digit is stored at the head of the array, and each element in the array stores only a single number.

You can assume that this integer will not start with a zero other than the integer 0.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The input array represents the digit 123.

Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The input array represents the digit 4321.

Example 3:

input: digits = [0]
output: [1]

Source: LeetCode
Link: https://leetcode-cn.com/problems/plus-one

analyze:

This is a very simple question. We can directly judge the length of the array to determine how many digits the number is, then traverse the array, multiply each element by the corresponding number of digits to get an integer number, and directly add one to the number , and finally store the number of each digit in the array.
However, I do not use this method. My method is similar to vertical addition, adding one to the last element of the array. If the last element is '9', we will traverse the array in reverse order and add the element of '9' Change to '0', and then continue to traverse forward, if it is not '9', we will '+1' the element, and finally if the first element of the array is still '9' after traversing, we will change it to is '1', and then add a '0' to the end of the array.

code:

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        n = len(digits) - 1 
        if n == 0 and digits[n] == 9: #数组元素长度为1,并且该元素为9
            digits[n] = 1
            digits.append(0) 
            return digits
        if digits[n] == 9: #末尾元素为9
            m = n
            while True:
                if m == n: #元素位置为末尾
                    digits[m] = 0 #将元素变为0
                m -= 1
                if digits[m] != 9: #末尾前一位元素不是9
                    digits[m] += 1  #元素 +1
                    return digits
                elif digits[m] == 9 and m == 0: #头元素为9
                    digits[m] =1  #将其变为1
                    digits.append(0)  #末尾加一个0
                    return digits
                else:
                    digits[m] = 0  #中间元素为9将其变为0
        else:
            digits[n] += 1  #末尾不为0,直接+1
        return digits

Eight, moving zero (simple)

topic:

Given an array nums, write a function to move all 0s to the end of the array while maintaining the relative order of the nonzero elements.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Source: LeetCode
Link: https://leetcode-cn.com/problems/move-zeroes

analyze:

This question is also a very simple question. We traverse the array. If the array element is '0', we can delete the element and add a '0' to the end of the array. This also ensures that it is not '0' The order of the elements.

code:

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        i = 0
        while True:
            if nums[i] == 0:
                nums.remove(0) #删除为0的元素
                nums.append(0) #向数组元素末尾添加0
                n -= 1
            else:
                i += 1
            if n == i:
                break


Nine, the sum of two numbers (simple)

topic:

Given an integer array nums and an integer target value target, please find the two integers whose sum is the target value target in the array, and return their array subscripts.

You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer.

You can return answers in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Source: LeetCode
Link: https://leetcode-cn.com/problems/two-sum

analyze:

This question is actually very easy to think of. It can be solved directly by violence. You can directly traverse the elements and then add them to get the target. In fact, it can be optimized. Subtract the target from the array elements to get the difference. Then we can judge whether the difference is in the array. If so, we can find the position of the difference in the array.

code:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        ans = [] #存两个元素的数组下标
        for i in range(len(nums)):
            n = target - nums[i] #差值
            if n in nums: #判断差值是否在数组中
                for j in range(len(nums)):
                    if j != i and nums[j] == n: #判断是否为元素值是否为差值和当前元素本身
                        ans.append(i)  
                        ans.append(j)
                        return(ans)

10. Effective Sudoku (moderate)

topic:

Please judge whether a 9 x 9 Sudoku is valid. You only need to verify whether the filled numbers are valid according to the following rules.

The numbers 1-9 can only appear once per line.
The numbers 1-9 can only appear once in each column.
Numbers 1-9 can only appear once in each 3x3 house separated by thick solid lines. (Please refer to the example picture)
insert image description here

Notice:

A valid Sudoku (partially filled) is not necessarily solvable.
You only need to verify whether the entered numbers are valid according to the above rules.
Blank cells are represented by '.'.

Example 1:

输入:board =
[[“5”,“3”,".",".",“7”,".",".",".","."]
,[“6”,".",".",“1”,“9”,“5”,".",".","."]
,[".",“9”,“8”,".",".",".",".",“6”,"."]
,[“8”,".",".",".",“6”,".",".",".",“3”]
,[“4”,".",".",“8”,".",“3”,".",".",“1”]
,[“7”,".",".",".",“2”,".",".",".",“6”]
,[".",“6”,".",".",".",".",“2”,“8”,"."]
,[".",".",".",“4”,“1”,“9”,".",".",“5”]
,[".",".",".",".",“8”,".",".",“7”,“9”]]
输出:true

Example 2:

输入:board =
[[“8”,“3”,".",".",“7”,".",".",".","."]
,[“6”,".",".",“1”,“9”,“5”,".",".","."]
,[".",“9”,“8”,".",".",".",".",“6”,"."]
,[“8”,".",".",".",“6”,".",".",".",“3”]
,[“4”,".",".",“8”,".",“3”,".",".",“1”]
,[“7”,".",".",".",“2”,".",".",".",“6”]
,[".",“6”,".",".",".",".",“2”,“8”,"."]
,[".",".",".",“4”,“1”,“9”,".",".: Except that the first number in the first row is changed from 5 to 8, the other numbers in the space are the same as Example 1. But since there are two 8s in the 3x3 house in the upper left corner, this Sudoku is invalid.Explanation
","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: false

Source: LeetCode
Link: https://leetcode-cn.com/problems/valid-sudoku

analyze:

The condition has been told in the title, which is to judge whether there are repeated numbers in each row, each column, and the 3*3 grid. As for how to judge whether there are repeated numbers, there are similar questions above.

code:

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        point = [[0,0],[0,3],[0,6],[3,0],[3,3],[3,6],[6,0],[6,3],[6,6]] #找出3*3宫格左上角元素
        for i in range(9): #判断行
            x = []
            for j in range(9):
                if board[i][j] != '.':
                    if board[i][j] in x:
                        return False
                    x.append(board[i][j])
        for i in range(9): #判断列
            y = []
            for j in range(9):
                if board[j][i] != '.':
                    if board[j][i] in y:
                        return False
                    y.append(board[j][i])           
        for p in range(9): #判断3*3宫格
            z = []
            a = point[p][0]
            b = point[p][1]
            for i in range(a,a + 3):
                for j in range(b,b + 3):
                    if board[i][j] != '.':
                        if board[i][j] in z:
                            return False
                        z.append(board[i][j])
        return True

11. Rotating images (medium)

topic:

Given an n × n two-dimensional matrix matrix representing an image. Please rotate the image 90 degrees clockwise.

You have to rotate the image in place, which means you need to directly modify the input 2D matrix. Please don't use another matrix to rotate the image.

Example 1:

insert image description in
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9 ,6,3]]
Example 2:

insert image description here
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15 ,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Source: LeetCode
Link: https://leetcode-cn.com/problems/rotate-image

analyze:

There are two methods for this question. The first method is to solve it directly by violence, which is obtained directly by transforming the elements of the array. However, I did not try this method because it is very complicated to write code.
The second is to change the array symmetrically up and down, and then perform symmetrical transformation according to the diagonal elements. You get the final result, you can draw a picture by yourself to see the result. I won't show any pictures here.

code:

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        l = len(matrix)
        n = l - 1
        for i in range(l//2):  #上下对称变换
            x = matrix[i]
            matrix[i] = matrix[n]
            matrix[n] = x
            n -= 1
        for i in range(l - 1):  #对角线对称变换
            for j in range(i + 1,l):
                x = matrix[i][j]
                matrix[i][j] = matrix[j][i]
                matrix[j][i] = x

The code word is not easy, give it a thumbs up.
I've seen it here, click a like and go.

Guess you like

Origin blog.csdn.net/youngwyj/article/details/122623537