leetcode - 260. Single Number III

这篇具有很好参考价值的文章主要介绍了leetcode - 260. Single Number III。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Description

Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

Example 1:

Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation:  [5, 3] is also a valid answer.

Example 2:

Input: nums = [-1,0]
Output: [-1,0]

Example 3:

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

Constraints:

2 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
Each integer in nums will appear twice, only two integers will appear once.

Solution

Sort

Use sort to get the sorted list, then use the pointer to iterate the whole list. When we see the element next to current element is identical, we move pointer 2 steps forward, otherwise we append the current element to list and move the pointer 1 step forward.

Time complexity: o ( n log ⁡ n ) o(n \log n) o(nlogn)
Space complexity: o ( 1 ) o(1) o(1)

Bit Manipulation

By xor all the element, we could get a ^ b, and it must contains 1 because a and b are two different numbers. We randomly select one digit that is 1 in a ^ b, then a and b are in different groups. One group has 1 in this digit while the other group has 0. We start over again to iterate the list, and all the other elements must be divided into these two groups. a will be the only single element in its group, and so does b. Then by xor we could get these two numbers.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( 1 ) o(1) o(1)文章来源地址https://www.toymoban.com/news/detail-503368.html

Code

Sort

class Solution:
    def singleNumber(self, nums: List[int]) -> List[int]:
        if len(nums) == 2:
            return nums
        nums.sort()
        res = []
        p = 0
        while p < len(nums):
            if p + 1 < len(nums) and nums[p] == nums[p + 1]:
                p += 2
            else:
                res.append(nums[p])
                p += 1
        return res

Bit Manipulation

class Solution:
    def singleNumber(self, nums: List[int]) -> List[int]:
        a_xor_b = 0
        for each_num in nums:
            a_xor_b ^= each_num
        digit = a_xor_b & (-a_xor_b)
        a_group, b_group = 0, 0
        for each_num in nums:
            if each_num & digit == 0:
                a_group ^= each_num
            else:
                b_group ^= each_num
        return [a_group, b_group]

到了这里,关于leetcode - 260. Single Number III的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • LeetCode992. Subarrays with K Different Integers

    Given an integer array nums and an integer k, return the number of good subarrays of nums. A good array is an array where the number of different integers in that array is exactly k. For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3. A subarray is a contiguous part of an array. Example 1: Input: nums = [1,2,1,2,3], k = 2 Output: 7 Explanation: S

    2024年01月20日
    浏览(35)
  • Leetcode 1325. Delete Leaves With a Given Value (二叉树后序遍历经典题)

    Delete Leaves With a Given Value Solved Medium Topics Companies Hint Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot)

    2024年02月22日
    浏览(43)
  • Leetcode 268. Missing Number

    Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Sum all the numbers as x x x and use n ( n + 1 ) 2 − x frac{n(n+1)}{2} - x 2 n ( n + 1 ) ​ − x .

    2024年02月14日
    浏览(39)
  • LeetCode447. Number of Boomerangs

    You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Return the number of boomerangs. Example 1: Input: points = [[0,0],[1,0],[2,0]] Output: 2 Explanation: The two boomerangs

    2024年02月02日
    浏览(34)
  • LeetCode每日一题(2457. Minimum Addition to Make Integer Beautiful)

    You are given two positive integers n and target. An integer is considered beautiful if the sum of its digits is less than or equal to target. Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful. Example 1: Input: n = 16, target = 6 Output: 4 Explanation: Init

    2023年04月16日
    浏览(95)
  • 【贪心】个人练习-Leetcode-2195. Append K Integers With Minimal Sum

    题目链接:https://leetcode.cn/problems/append-k-integers-with-minimal-sum/ 题目大意:给出一个数组 nums[] ,现在要往里面追加 k 个【互不相同】且【未出现在 nums[] 中】的【正整数】,使得这 k 个数字之和最小。 思路:明显就是贪心,从 1 开始塞进去即可。但是单纯的【累加+用set判断是

    2024年02月02日
    浏览(47)
  • LeetCode171. Excel Sheet Column Number

    Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number. For example: A - 1 B - 2 C - 3 … Z - 26 AA - 27 AB - 28 … Example 1: Input: columnTitle = “A” Output: 1 Example 2: Input: columnTitle = “AB” Output: 28 Example 3: Input: columnTitle = “ZY” Output: 701 Constraints:

    2024年02月19日
    浏览(40)
  • LeetCode287. Find the Duplicate Number

    Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space. Example 1: Input: nums = [1,3,4,2,2] Output: 2 Example 2: Input: nums = [3,1,3,4,

    2024年01月20日
    浏览(43)
  • LeetCode 933. Number of Recent Calls

    ou have a  RecentCounter  class which counts the number of recent requests within a certain time frame. Implement the  RecentCounter  class: RecentCounter()  Initializes the counter with zero recent requests. int ping(int t)  Adds a new request at time  t , where  t  represents some time in milliseconds, and returns the number of requests that has h

    2024年02月08日
    浏览(46)
  • Leetcode 313: Super Ugly Number (超级丑数)

    Super Ugly Number Medium A super ugly number is a positive integer whose prime factors are in the array primes. Given an integer n and an array of integers primes, return the nth super ugly number. The nth super ugly number is guaranteed to fit in a 32-bit signed integer. Example 1: Input: n = 12, primes = [2,7,13,19] Output: 32 Explanation: [1,2,4,7,8,13,14

    2024年02月07日
    浏览(27)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包