Xiao Li Feidao: The eleventh bullet!

Keywords: Python MATLAB less

Written in front

Recently, I have been busy with teaching new equipment. I haven't written problems in time, but I haven't been lazy and I haven't brushed them.~
Come and sort out the latest topics carefully.~

Before I thought about using tag to brush the questions, I received the recommended leetcode problem, and I brushed the questions one after another according to the above instructions.~
tag mainly do: array, double pointer
It's time to start deploying gitbook, and then deploy the solution to the ebook~

The dividing line of serious problem-solving

First question

387. The first unique character in a string
Difficulty: Simple
Given a string, find its first non-repeating character and return its index. If it does not exist, return - 1.

Case study:
s = "leetcode"
Return to 0.
s = "loveleetcode",
Return to 2.

My problem:

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        mapa = dict()
        for i in s:
            if i not in mapa:
                mapa[i] = 1
            else:
                mapa[i] += 1
        for j in range(len(s)):
            a = s[j]
            if a in mapa and mapa[a] == 1:
                return j
        return -1

My thoughts:

Second questions

283. Moving Zero
Difficulty: Simple
Given an array nums, write a function to move all 0 to the end of the array while maintaining the relative order of non-zero elements.

Case study:
Input: [0, 1, 0, 3, 12]
Output: [1,3,12,0,0]
Return to 2.

My problem:

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        l = len(nums)
        j = 0
        for i in range(l):
            if nums[i] !=0:
                nums[j] = nums[i]
                j +=1
        nums[j:l] = [0 for i in range(l-j)]

My thoughts:

Third questions

268. Missing figures
Difficulty: Simple
Given a sequence containing N numbers in 0, 1, 2,..., n, find the number that does not appear in the sequence in 0.. N.

Case study:
Input: [3, 0, 1]
Output: 2
Input: [9, 6, 4, 2, 3, 5, 7, 0, 1]
Output: 8

My problem:

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sum = 0
        l =len(nums)
        sum_a = (1+l)*l/2
        for i in nums:
            sum += i
        return sum_a - sum```

Fourth questions

229. Solving the Mode II
Difficulty: Simple
Given an array of size n, find out all elements that appear more than n/3 times.

Explanation: The time complexity and space complexity of the algorithm are required to be O(n) and O(1).

Case study:
Input: [3, 2, 3]
Output: [3]
Input: [1, 1, 1, 3, 3, 2, 2, 2]
Output: [1,2]

My problem:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """ 
        a = dict()
        b = list()
        n = len(nums) / 3
        for i in nums:
            if i not in a:
                a[i] = 1
            else:
                a[i] += 1
        for j in a:
            if a[j] > n:
                b.append(j)
        return b

My thoughts:

Fifth questions

101. Symmetric Binary Tree
Difficulty: Simple
Given a binary tree, check whether it is mirror symmetric.
For example, binary trees [1, 2, 2, 3, 4, 4, 3] are symmetrical.
But the following [1,2,2,null,3,null,3] is not mirror symmetric:

My problem:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        return self.isSame(root.left,root.right)
    
    def isSame(self,leftNode,rightNode):
        if leftNode == None:
            return rightNode == None
        if rightNode == None:
            return leftNode == None
        if rightNode.val == leftNode.val:
            return self.isSame(leftNode.left,rightNode.right) and self.isSame(leftNode.right,rightNode.left)
        return False


My thoughts:

Sixth questions

905. Array sorted by parity
Difficulty: Simple
Given a nonnegative integer array A, it returns an array of all even elements of A followed by all odd elements of A.
You can return any array that satisfies this condition as an answer.

Example:
Input: [3, 1, 2, 4]
Output: [2,4,3,1]
Output [4, 2, 3, 1], [2, 4, 1, 3] and [4, 2, 1, 3] will also be accepted.

My problem:

class Solution(object):
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        n = [0]*len(A)
        k = 0
        j = len(A) - 1
        for i in range(len(A)):
            if A[i] % 2 ==1: #Odd number
                n[j] = A[i]
                j -= 1
            else:
                n[k] = A[i]
                k += 1
        return n


My thoughts:

Seventh questions

832. Flip image
Difficulty: Simple
Given a binary matrix A, we want to flip the image horizontally, then reverse the image and return the result.
Horizontal flip image is to flip every line of the image, that is, reverse order. For example, the result of horizontal flip [1, 1, 0] is [0, 1, 1].
The reverse image means that all 0 in the image is replaced by 1 and all 1 is replaced by 0. For example, the result of reversing [0, 1, 1] is [1, 0, 0].

My problem:

class Solution(object):
    def flipAndInvertImage(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        #Reverse order
        return [[j ^ 1 for j in i[::-1]] for i in A]


My thoughts:

Eighth questions

922. Array by parity II
Difficulty: Simple
Given a nonnegative integer array A, half of the integers in A are odd and half of the integers are even.
Sort arrays so that when A[i] is odd, I is also odd; when A[i] is even, I is even.
You can return any array that meets the above criteria as an answer.

My problem:

class Solution(object):
    def sortArrayByParityII(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        count0 = 0
        count1 = 1
        re = []
        for i in A:
            if i%2 == 0:
                re.insert(count0, i)
                count0 += 2
            else:
                re.insert(count1, i)
                count1 += 2
        return re


My thoughts:

Ninth questions

509. Fibonacci number
Difficulty: Simple
Fibonacci number, usually expressed in F(n), is called Fibonacci sequence. The sequence starts with 0 and 1, and each number that follows is the sum of the first two numbers. That is:

F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), where N > 1.

Given N, calculate F(N).

My problem:

class Solution(object):
    def fib(self, N):
        """
        :type N: int
        :rtype: int
        """
        if N == 0:return 0
        if N==1 or N == 2:return 1
        return (self.fib(N-1)+self.fib(N-2))

My thoughts:

Tenth questions

561. Array splitting I
Difficulty: Simple
Given an array of length 2n, your task is to divide these numbers into n pairs, such as (a1, b1), (a2, b2),..., (an, bn), so that the sum of min(ai, bi) from 1 to n is maximum.

Input: [1, 4, 3, 2]

Output: 4
Interpretation: n equals 2, and the maximum sum is 4 = min(1, 2) + min(3, 4).

Tips:
n is a positive integer with a range of [1,10000].
The range of elements in the array is [-10000, 10000].

My problem:

class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return sum(nums[::2])


My thoughts:

Eleventh questions

867. Transpose Matrix
Difficulty: Simple
Given a matrix A, return the transpose matrix of A.
Matrix inversion refers to the reversal of the principal diagonal of the matrix and the exchange of row and column indexes of the matrix.
My problem:

class Solution(object):
    def transpose(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        return zip(*A)


My thoughts:

Twelfth questions

1002. Find Common Characters
Difficulty: Simple
Given a string array A consisting of only lowercase letters, it returns a list of all characters (including duplicate characters) displayed in each string in the list. For example, if a character appears three times in each string, but not four times, it needs to be included three times in the final answer.
You can return the answers in any order.
Example 1:

Input: ["bella","label","roller"]
Output: ["e","l","l"]

My problem:

class Solution(object):
    def commonChars(self, A):
        """
        :type A: List[str]
        :rtype: List[str]
        """
        tmp = list(A[0])
        for i in range(1,len(A)):
            tmp_list =list()
            for j in A[i]:
                if j in tmp:
                    index = tmp.index(j)
                    del tmp[index]
                    tmp_list.append(j)
            tmp = tmp_list
        return tmp


My thoughts:

Thirteenth questions

350. The intersection of two arrays II
Difficulty: Simple
Given two arrays, write a function to compute their intersection.

Example 1:

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

Explain:
The number of occurrences of each element in the output should be the same as the number of occurrences of elements in two arrays.
We can ignore the order of output.

My problem:

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        l = list()
        for i in nums2:
            if i in nums1:
                index = nums1.index(i)
                del nums1[index]
                l.append(i)
        return l


My thoughts:

Fourteenth questions

1002. Find Common Characters
Difficulty: Simple
Given two arrays, write a function to compute their intersection.

Example:

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

Explain:
Each element in the output must be unique.
We can ignore the order of output.

My problem:

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        l = dict()
        a = list()
        for i in nums2:
            if i in nums1:
                if i not in l:
                    l[i] = 1
        for key in l:
            a.append(key)
        return a


My thoughts:

Fifteenth questions

566. Rebuilding Matrix
Difficulty: Simple
In MATLAB, there is a very useful function reshape, which can reshape a matrix into another new matrix of different sizes, but retain its original data.
A matrix represented by a two-dimensional array and two positive integers r and c are given to represent the number of rows and columns of the reconstructed matrix.
The reconstructed matrix needs to fill all elements of the original matrix in the same row traversal order.
If the reshape operation with a given parameter is feasible and reasonable, a new reshape matrix is output; otherwise, the original matrix is output.
Example:

Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Interpretation:
The result of traversing nums is [1,2,3,4]. The new matrix is a * 4 matrix. The new matrix is filled in row by row with the previous element values.
My problem:

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        l_a = len(nums)
        l_b = len(nums[0])
        if l_a*l_b != r*c:
            return nums
        if l_a == r:
            return nums
        list_a = list()
        list_b = list()
        count = 0
        for i in range(l_a):
            for j in range(l_b):
                list_b.append(nums[i][j])
                count += 1
                if count == c:
                    list_a.append(list_b)
                    list_b = list()
                    count = 0
        return list_a

My thoughts:

Sixteenth questions

485. Number of Maximum Continuous 1
Difficulty: Simple
Given a binary array, the number of the most continuous 1 is calculated.

Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Interpretation: The first two and the last three are consecutive 1, so the maximum number of consecutive 1 is 3.

Be careful:
The input array contains only 0 and 1.
The length of the input array is a positive integer and does not exceed 10,000.

My problem:

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max_l = 0
        count = 0
        for i in nums:
            if i == 1 :
                count +=1
            else: ###Encounter 0
                if count > max_l:
                    max_l = count
                count = 0
        if count > max_l:
            max_l = count             
        return max_l


My thoughts:

Seventeenth questions

167. Sum of Two Numbers II - Input Ordered Array
Difficulty: Simple
Given an ordered array arranged in ascending order, find two numbers so that the sum of them equals the target number.

The function should return the two subscript values index1 and index2, where index1 must be less than index2.

Explain:

  • The returned subscripts (index1 and index2) are not zero-based.
  • You can assume that each input corresponds to only one answer, and you can't reuse the same elements.

My problem:

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        l = len(numbers)
        i = 0
        j = l - 1
        l_a = list()
        while  i < j:
            if numbers[i]+numbers[j] == target:
                l_a.append(i+1)
                l_a.append(j+1)
                return l_a
            elif numbers[i]+numbers[j] > target:
                j -= 1
            else:
                i +=1
        return null

My thoughts:

Eighteenth questions

633. Sum of squares
Difficulty: Simple
Given a nonnegative integer c, you need to determine whether there are two integers a and B so that a_+b_= C.

Example:

Input: 5
Output: True
Interpretation: 1 1 + 2 2 = 5

My problem:

import math
class Solution(object):
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        a = int(math.sqrt(c))
        b = 0
        while a > b:
            if a**2 + b**2 == c:
                return True
            elif a**2 + b**2 > c:
                a -= 1
            else:
                b += 1
        if a**2 + b**2 == c:
            return True
        else:
            return False           


My thoughts:

Nineteenth questions

345. Inversion of vowel letters in strings
Difficulty: Simple
Write a function that takes a string as input and inverts the vowel letters in the string.
Example:

Input: "hello"
Output: "holle"

My problem:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        y = ['a','e','i','o','u','A','E','I','O','U']
        p = 0 
        q = len(s) - 1
        s = list(s)
        while p<=q:
            if s[q] not in y and s[p] not in y:
                p += 1
                q -= 1
            elif s[p] in y and s[q] not in y:
                q -= 1
            elif s[q] in y and s[p] not in y:
                p += 1
            else:
                flag = s[q]
                s[q] = s[p]
                s[p] = flag
                p += 1
                q -= 1
        return ''.join(s)


My thoughts:

Twentieth questions

141. Ring list
Difficulty: Simple
Given a linked list, determine whether there are rings in the linked list.
To represent rings in a given list, we use the integer pos to represent the location where the end of the list is connected to the list (the index starts at 0). If pos is - 1, there are no rings in the list.

My problem:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head:
            return False
        l1 = head
        l2 = head.next
        while l1 and l2 and l2.next:
            if l1 == l2:
                return True
            l1 = l1.next
            l2 = l2.next.next
        return False

My thoughts:

Question 21

985. Even sum after query
Difficulty: Simple
Given an integer array A and a query array queries.

For the first query, val=queriesi, index = queries i We'll add value to A[index]. Then, the answer to the first query is the sum of even values in A.

(The index given here = queries i The index starts at 0, and every query permanently modifies the array A.)

Returns the answers to all queries. Your answer should be given in an array of answers, with answer[i] as the answer for the first query.

My problem:

class Solution(object):
    def sumEvenAfterQueries(self, A, queries):
        """
        :type A: List[int]
        :type queries: List[List[int]]
        :rtype: List[int]
        """
        l =list()
        sum = 0
        sum_a = 0
        for j in A:
            if j%2 ==0:
                sum_a += j
        for i in range(len(queries)):
            A[queries[i][1]] += queries[i][0]#Increase in numerical value
            if A[queries[i][1]] % 2 ==0:#Even numbers
                if queries[i][0]%2 ==0:#Even numbers
                    sum = sum_a + queries[i][0]
                else:#is odd
                    sum = sum_a +  A[queries[i][1]]
            else:#is odd
                if queries[i][0]%2 ==0:#Even numbers
                    sum = sum_a
                else:
                    sum = sum_a - A[queries[i][1]] + queries[i][0]
            l.append(sum)
            sum_a =sum
        return l


My train of thought

Small summary

Posted by The End on Mon, 06 May 2019 09:00:39 -0700