Primary Algorithms--LeetCode Beginners

Deliberate Practice: Remember First, Then Be Autonomous

array

- Numbers that appear only once

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.
Explanation:
Your algorithm should have linear time complexity. Can you do it without using extra space?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        for num in nums:
            if nums.count(num) == 1:
                return num

- rotate the array

Given an array, shift the elements in the array to the right by k positions, where k is a non-negative number.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
Rotate right by 1 step: [ 7,1,2,3,4,5,6]
Rotate 2 steps to the right: [6,7,1,2,3,4,5]
Rotate 3 steps to the right: [5,6,7,1, 2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
Rotate right 1 step: [99, -1,-100,3]
Rotate right 2 steps: [3,99,-1,-100]
Explanation:
Come up with as many solutions as possible, there are at least three different ways to solve this problem.
An in-place algorithm with O(1) space complexity is required.

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        k = k % len(nums)
        nums[:] = nums[-k:] + nums[:-k]

LC Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

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]

illustrate:

The number of occurrences of each element in the output result should be consistent with the minimum value of the number of occurrences of the element in the two arrays.
We can ignore the order of the output results.
Advanced:

What if the given array is already sorted? How would you optimize your algorithm?
If the size of nums1 is much smaller than nums2, which method is better?
What do you do if the elements of nums2 are stored on disk, memory is limited, and you cannot load all elements into memory at once?

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        n1 = nums2 if len(nums1) >= len(nums2) else nums1
        n2 = nums2 if len(nums1) < len(nums2) else nums1
        ans = []
        for i in n1:
            if i in n2:
                ans.append(i)
                n2.remove(i)
        return ans

Guess you like

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