iT邦幫忙

2022 iThome 鐵人賽

DAY 11
0
自我挑戰組

LeetCode Top 100 Liked系列 第 11

[Day 11] 136. Single Number (Easy)

  • 分享至 

  • xImage
  •  

136. Single Number

Question

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one
You must implement a solution with a linear runtime complexity and use only constant extra space

Example 2

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

Solution 1: Brute Force

Time Complexity: O(N^2)
Space Complexity: O(1)

Solution 2: Sorting + Linear Search

Time Complexity: O(N*Log(N))
Space Complexity: O(1)

Solution 3: Hash Counter

Time Complexity: O(N)
Space Complexity: O(N)

Solution 4: Set

Time Complexity: O(N)
Space Complexity: O(N)

Solution 5: XOR

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        ans = nums[0]
        for i in range(1, len(nums)):
            ans ^= nums[i]
        return ans

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

Reference

https://leetcode.com/problems/single-number/discuss/1771771/Think-it-through-oror-Time%3A-O(n)-Space%3A-O(1)-oror-Python-Explained

Follow-up List:

  • Single Number II
  • Medium
  • Single Number III
  • Medium
  • Missing Number
  • Easy
  • Find the Duplicate Number
  • Medium
  • Find the Difference
TODO

Time Complexity: O()
Space Complexity: O()


上一篇
[Day 10] Remove Duplicates from Sorted Array (Easy)
下一篇
[Day 12] Generate Parentheses (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言