Beginners: Arrays & Strings

Target

1. Understand the difference between arrays and dynamic arrays.

2. Familiar with basic operations in arrays and dynamic arrays.

3. Understand multidimensional arrays and be able to master the use of two-dimensional arrays.

4. Understand the concept of strings and the different characteristics of strings.

5. Be able to use the double-pointer technique to solve practical problems.

Introduction to Arrays

数组Is a basic data structure used to sort by 存储元素的集合. But the elements can be accessed randomly because each element in the array can be 索引identified by the array.

Arrays can have one or more dimensions. Here we 一维数组start with , which is also known as a linear array.

Introduction to Dynamic Arrays

Arrays have 固定的容量, we need to specify the size of the array at initialization time. Sometimes it can be very inconvenient and potentially wasteful.

As such, most programming languages ​​provide a built-in 动态数组, which is still a random-access list data structure, but 大小是可变的.

Find the middle index of an array

Given an array of integer types  nums, write a method that returns the "center index" of the array.

We define the array center index like this : the sum of all elements on the left of the array center index is equal to the sum of all elements on the right.

If the array does not have a center index, then we should return -1. If the array has more than one center index, then we should return the one closest to the left.

Example 1:

输入: 
nums = [1, 7, 3, 6, 5, 6]
输出: 3
解释: 
索引3 (nums[3] = 6) 的左侧数之和(1 + 7 + 3 = 11),与右侧数之和(5 + 6 = 11)相等。
同时, 3 也是第一个符合要求的中心索引。

Example 2:

输入: 
nums = [1, 2, 3]
输出: -1
解释: 
数组中不存在满足此条件的中心索引。

illustrate:

  • nums The length range is  [0, 10000].
  • Either  nums[i] will be an  [-1000, 1000]integer in the range .
class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        if len(nums) < 3:
            return -1
        for i in range(len(nums)):
            if sum(nums[:i]) == sum(nums[i+1:]):
                return i
        return -1
        

The largest number that is at least twice the other data

In a given array nums, there is always a maximum element.

Finds if the largest element in an array is at least twice every other number in the array.

If yes, returns the index of the largest element, otherwise -1.

Example 1:

输入: nums = [3, 6, 1, 0]
输出: 1
解释: 6是最大的整数, 对于数组中的其他整数,
6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.

 

Example 2:

输入: nums = [1, 2, 3, 4]
输出: -1
解释: 4没有超过3的两倍大, 所以我们返回 -1.

 

hint:

  1. nums The length range is [1, 50].
  2. Each  nums[i] integer ranges from  [0, 100].
class Solution:
    def dominantIndex(self, nums: List[int]) -> int:
        nums_max = max(nums)
        ind = nums.index(nums_max)
        tmp = []
        for item in nums:
            if nums_max >= 2 * item or item == nums_max:
                tmp.append(item)
        if len(tmp) == len(nums) :
            return ind
        else:
            return -1

plus one

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:

输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。

Example 2:

输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。
class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        n=len(digits)
        for i in range(n-1,-1,-1):
            if digits[i]<9:
                digits[i]+=1
                return digits
            else:
                digits[i]=0
        return [1]+digits

search caret position

Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position where it will be inserted in order. You can assume that there are no duplicate elements in the array.

Example 1:

输入: [1,3,5,6], 5
输出: 2
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        for i in range(0, len(nums)):
            if nums[i] >= target:
                return i
            elif i == len(nums) - 1:
                return len(nums)

merge interval

Given a set of intervals, merge all overlapping intervals.

Example 1:

输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        res = []
        intervals.sort()
        for i in intervals:
            if not res or res[-1][1]<i[0]:
                res.append(i)
            else:
                res[-1][1] = max(res[-1][1],i[1])
        return res

Introduction to 2D Data

Multidimensional arrays are better suited for complex structures like tables or matrices.

learning target:

1. How is a two-dimensional array stored in memory?

2. How to use two-dimensional arrays to solve problems

rotation matrix

You are given an  N × N image represented by a matrix where each pixel is 4 bytes in size. Please design an algorithm to rotate the image by 90 degrees.

Can it be done without taking up extra memory space?

Example 1:

给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵,使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]
class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        # 先上下镜面翻转
        for i in range(n // 2):
            for j in range(n):
                matrix[i][j], matrix[n - 1 - i][j] = matrix[n - 1 - i][j], matrix[i][j]
        
        # 再主对角线翻转
        for i in range(n):
            for j in range(i):
                matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]

zero matrix

Write an algorithm to clear the row and column where an element in an M × N matrix is ​​0.

Example 1:

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

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        rownum = len(matrix)
        colnum = len(matrix[0])
        row = [False for i in range(rownum)]
        col = [False for i in range(colnum)]
        for i in range(rownum):
            for j in range(colnum):
                if matrix[i][j] == 0:
                    row[i] = True
                    col[j] = True
        for i in range(rownum):
            for j in range(colnum):
                if row[i] or col[j]:
                    matrix[i][j] = 0

diagonal traversal

Given a matrix with M x N elements (M rows, N columns), please return all elements in this matrix in the order of diagonal traversal, as shown in the figure below.

 

Example:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

Output: [1,2,4,7,5,3,6,8,9]

explain:


Author: LeetCode
Link: https://leetcode-cn.com/leetbook/read/array-and-string/cuxq3/
Source: LeetCode
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

class Solution:
    def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
        m = len(matrix)
        if not m:
            return []
        n = len(matrix[0])
        if not n:
            return []
        matrix_num = m*n
 
        count = 0
        x = y = 0
        li = []
        direction = "up"
        while count < matrix_num:
            count += 1
            li.append(matrix[x][y])
            # 右上方向
            if direction == "up":
                # 无需调换方向的条件(1.x>0 碰到上壁前, 2.y<n-1碰到右壁前)
                if x > 0 and y < n-1:
                     x -= 1
                     y += 1
                     continue
                else:
                    direction = "down"
                    # 碰到上壁 x=0
                    if x == 0 and y < n-1:
                        y += 1
                    # 碰到右壁
                    elif y == n-1:
                        x += 1
            # 左下方向
            else:
                # 无需调换方向的条件(1.x<m 碰到下壁前, 2.y>0 碰到右壁前)
                if x < m-1 and y > 0:
                    x += 1
                    y -= 1
                    continue
                else:
                    direction = "up"
                    if x == m-1:
                        y += 1
                    elif y == 0 and x < m-1:
                        x += 1
        return li

Introduction to Strings

A string is an array of characters.

learning target:

1. Be familiar with the basic operations in strings, especially the unique operations that are not available in arrays;
2. Understand the differences between different comparison functions;
3. Understand whether strings are mutable and cause problems in the connection process;
4. Able to solve basic problems related to strings, such as sorting, substrings, string matching, etc.

longest common prefix

Write a function to find the longest common prefix in an array of strings.

Returns the empty string "" if no common prefix exists.

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix for the input.
illustrate:

All inputs contain only lowercase letters az .

Author: LeetCode
Link: https://leetcode-cn.com/leetbook/read/array-and-string/ceda1/
Source: LeetCode
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        import os
        return os.path.commonprefix(strs)

longest palindromic substring

Given a string s, find the longest palindromic substring in s. You can assume that s has a maximum length of 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:

Input: "cbbd"
Output: "bb"

Author: LeetCode
Link: https://leetcode-cn.com/leetbook/read/array-and-string/conm7/
Source: LeetCode
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

class Solution:
    def longestPalindrome(self, s: str) -> str:
        max_length = 0
        start = 0
        for i in range(len(s)):
            if i - max_length >= 1 and s[i-max_length-1: i+1] == s[i-max_length-1: i+1][::-1]:
                start = i - max_length - 1
                max_length +=2
                continue
            if i - max_length >= 0 and s[i-max_length: i+1] == s[i-max_length: i+1][::-1]:
                start = i - max_length
                max_length += 1
        return s[start: start+max_length]

flip words in a string

Given a string, flip each word in the string one by one.

 

Example 1:

Input: " the sky is blue"
 Output:  " blue is sky the"
class Solution:
    def reverseWords(self, s: str) -> str:
        li = s.split(" ")
        str = ""
        for i in range(len(li)-1, -1, -1):
            if li[i]:
                str = str + li[i] + " "
        # 因为最后一个单词多加了一个空格符“ ”          
        return str[:-1] 

String matching algorithm: KMP

The Knuth–Morris–Pratt (KMP) algorithm is an improved string matching algorithm. Its core is to use the information after the matching fails to minimize the number of matches between the pattern string and the main string to achieve the purpose of fast matching. Its time complexity is O(m+n)O(m+n)O(m+n).

int match (char* P, char* S){ // KMP 算法
    int* next = buildNext(P); // 构造 next 表
    int m = (int) strlen (S), i = 0; // 文本串指针
    int n = (int) strlen(P), j = 0; //模式串指针
    while (j < n && i < m) // 自左向右逐个比对字符
        if (0 > j || S[i] == P[j]) // 若匹配,或 P 已移除最左侧
            {i++; j++} // 则转到下一字符
        else
            j = next[j]; // 模式串右移(注意:文本串不用回退)
    delete [] next; // 释放 next 表
    return i - j;
}

Implement strStr()

Implement the strStr() function.

Given a haystack string and a needle string, find the first position (starting from 0) of the needle string in the haystack string. Returns -1 if not present.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1
Explanation:

What should we return when needle is an empty string? This is a great question to ask in an interview.

For this question, we should return 0 when needle is an empty string. This matches the definition of strstr() in C and indexOf() in Java.

Author: LeetCode
Link: https://leetcode-cn.com/leetbook/read/array-and-string/cm5e2/
Source: LeetCode
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        for i in range(0, len(haystack) - len(needle) + 1):
            if haystack[i: i + len(needle)] == needle:
                return i
        return -1

two-pointer technique

Two Pointer Technique Scenario 1

Reverses the elements in the array. For example, the array is ['l', 'e', ​​'e', ​​'t', 'c', 'o', 'd', 'e'], after inversion becomes ['e', 'd' , 'o', 'c', 't', 'e', ​​'e', ​​'l'].

def reverseString(self, s):
        i, j = 0, len(s) - 1
        while i < j:
            s[i], s[j] = s[j], s[i]
            i += 1
            j -= 1

reverse string

Write a function that reverses the input string. The input string is given as a char[] array of characters.

Don't allocate extra space for another array, you have to modify the input array in-place, using O(1) extra space to solve this problem.

You can assume that all characters in the array are printable characters in the ASCII code table.

 

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:

输入:["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

Author: LeetCode
Link: https://leetcode-cn.com/leetbook/read/array-and-string/cacxi/
Source: LeetCode
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        j=-1
        for i in range(0,len(s)//2):
            t=s[i]
            s[i]=s[j]
            s[j]=t
            j-=1

Double Pointer Technique Scenario 2

Use two unsynchronized pointers to solve the problem, the fast and slow pointers.

example


Let's start with a classic problem:

Given an array  nums and a value  val, you need to   remove all elements equal to the value  in placeval  , and return the new length of the removed array.

 

def removeElement(self, nums: List[int], val: int) -> int:
    slow = 0
    n = len(nums)
    for fast in range(n):
        if nums[fast] != val:
            nums[slow] = nums[fast]
            slow += 1
    return slow

remove element

Given an array nums and a value val, you need to remove all elements whose value is equal to val in place, and return the new length of the removed array.

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

The order of elements can be changed. You don't need to consider elements in the array beyond the new length.

 

Example 1:

Given nums = [3,2,2,3], val = 3,

The function should return the new length 2, and the first two elements in nums are both 2.

You don't need to consider elements in the array beyond the new length.

illustrate:

Why is the returned value an integer, but the output answer is an array?

Note that the input array is passed "by reference", which means that modifications to the input array within the function are visible to the caller.

You can imagine the internal operation as follows:

// nums is passed by "reference". That is, do not make any copies of the actual parameters
int len ​​= removeElement(nums, val);

// Modifications to the input array in the function are visible to the caller.
// Depending on the length returned by your function, it will print out all the elements in the array within that length.
for (int i = 0; i < len; i++) {     print(nums[i]); }

Author: LeetCode
Link: https://leetcode-cn.com/leetbook/read/array-and-string/cwuyj/
Source: LeetCode
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        while val in nums:
            nums.remove(val)
        return len(nums)

summary

Array related technologies

1, here are some other array-like data structures, but with some different properties:

String
Hash Table
Linked List
Queue
Stack
2, as we mentioned, we can call built-in functions to sort the array. However, it is useful to understand the principles of some widely used sorting algorithms and their complexities.

3. Binary search is also an important technique for searching a specific element in a sorted array.

4. We have introduced the double pointer technique in this chapter. It is not easy to use this technique flexibly. This trick can also be used to solve:

The problem of slow pointer and fast pointer in the linked list
Sliding window problem
5, the double pointer technique is sometimes related to the greedy algorithm, which can help us design the movement strategy of the pointer. 

Guess you like

Origin blog.csdn.net/weixin_42748604/article/details/106097306