[剑指Offer] Day 4: Searching

Authored by Tony Feng

Created on April 15th, 2022

Last Modified on April 15th, 2022

Task 1 - Q03. 数组中重复的数字

Question

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

Solution 1

1
2
3
4
5
6
7
8
class Solution: # Hash Map
    def findRepeatNumber(self, nums: List[int]) -> int:
        dict = {} 
        for n in nums:
            if n in dict:
                return n
            dict[n] = 1
        return -1

Solution 2

1
2
3
4
5
6
7
8
class Solution: # Set
    def findRepeatNumber(self, nums: [int]) -> int:
        s = set()
        for num in nums:
            if num in s: 
                return num
            s.add(num)
        return -1

Explanation

  • Solution1 and 2 use the same idea but different data structures.
  • Time Complexity: O(N)
  • Space Complexity: O(N)

Task 2 - Q53,I. 在排序数组中查找数字 I

Question

统计一个数字在排序数组中出现的次数。

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution: # Bianry Search
    '''
    Find the right bound of target and target-1
    '''
    def search(self, nums: [int], target: int) -> int:
        def findR(tar):
            i, j = 0, len(nums) - 1
            while i <= j:
                m = i + (j - i) // 2
                if nums[m] <= tar: 
                    i = m + 1
                else: 
                    j = m - 1
            return i
        return findR(target) - findR(target - 1)

Explanation

  • Time Complexity: O(log N)
  • Space Complexity: O(1)

Task 3 - Q53,II. 0~n-1中缺失的数字

Question

一个长度为n-1递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
'''
Find the rightest index that is not equal to its element
'''
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        i, j = 0, len(nums)-1
        while i <= j:
            m = i + (j - i) // 2
            if m == nums[m]:
                i = m + 1
            else:
                j = m - 1

        return i

Explanation

  • Time Complexity: O(log N)
  • Space Complexity: O(1)

MIT License
Last updated on May 18, 2022 05:41 EDT
Built with Hugo
Theme Stack designed by Jimmy