//GitHub https://github.com/vellimole0621
137. Single Number II
문제 - https://leetcode.com/problems/single-number-ii/
문제 설명
Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.
You must implement a solution with a linear runtime complexity and use only constant extra space.
=> 주어진 배열은 한 원소를 제외하고, 중복으로 셋 씩 들어있다. 중복이 아닌 한 원소를 찾아라.
내 풀이 :
set() 함수로 주어진 배열에서 중복을 제외함 > 중복이 제외된 배열과 기존 배열을 이중 반복문으로 비교해서 중복 아닌 원소 찾음
class Solution:
def singleNumber(self, nums) -> int:
list_num = list(set(nums))
for i in range(0, len(list_num)):
a = 0
for j in range(0, len(nums)):
if list_num[i] == nums[j]:
a = a + 1
if a == 1:
return list_num[i]
break
LeetCode에서 찾은 더 나은 풀이 :
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return (3*sum(set(nums)) - sum(nums))//2
기존 배열의 원소 중 결국 셋이 아닌 원소는 하나 뿐이니까.
1. set()*3 으로 전부 다 셋으로 만듦 > 2. 거기에 기존의 배열 합으로 뺌 > 3. 그렇게 한 다음 2로 나눠서 찾음
'프로그래밍 > Python' 카테고리의 다른 글
[파이썬 Python/알고리즘] LeetCode - Valid Perfect Square (0) | 2023.07.19 |
---|---|
[파이썬 Python/알고리즘] LeetCode - Unique Paths (0) | 2023.07.16 |
[파이썬 Python/알고리즘] LeetCode - Buddy Strings (0) | 2023.07.03 |
[파이썬 Python/알고리즘] LeetCode - Palindrome Number (0) | 2023.07.02 |
[파이썬 Python/알고리즘] LeetCode - Two Sum (0) | 2023.06.30 |