Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

ashwins-code
ashwins-code

Posted on

     

Leetcode Problem 260: Single Number III

Hi! Welcome to today's post which is a solution to Leetcode Problem 260. This question is a Medium level difficulty question. Here's the solution on GitHubhttps://github.com/ashwins-code/leetcode-solutions/blob/main/medium/problem260-single-number-iii.py

The Question

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.

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]
Enter fullscreen modeExit fullscreen mode

Solution

We can start off with an empty list (ans) and go through thenums list. For each element in thenums list, we append this toans if we haven't encountered this element before (we know this by checking if the element is already inans). If we have encountered it, remove this element fromans. After we have finished iterating through nums,ans should only contain the numbers which appeared once. Here's an example

nums = [1,2,1,3,2,5]ans = []Go through nums1 => add this to ans as we have never seen this before (ans = [1])2  => add this to ans as we have never seen this before (ans = [1, 2])1 => remove this from ans as we have seen this before (ans = [2])3 => add this to ans as we have never seen this before (ans = [2, 3])2 => remove this from ans as we have seen this before (ans = [3])5 => add this to ans as we have never seen this before (ans = [3, 5])Ans now has the correct answer
Enter fullscreen modeExit fullscreen mode

The Code

classSolution:defsingleNumber(self,nums:List[int])->List[int]:ans=[]foriinnums:ifinotinans:ans.append(i)else:ans.remove(i)returnans
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A 17-year-old student who would love to get into an ML career in the future! Please visit my Github at https://github.com/ashwins-code
  • Location
    London
  • Work
    Student
  • Joined

More fromashwins-code

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp