엔지니어 게시판
LeetCode 솔루션 분류

[Easy - wk6 - Q2] 136. Single Number

컨텐츠 정보

본문

136. Single Number 


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 1:

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

Example 2:

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

Example 3:

Input: nums = [1]
Output: 1

 

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.

관련자료

댓글 3

namsoo님의 댓글

  • 익명
  • 작성일
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
     
        nhash = defaultdict(int)
       
        for n in nums:
            nhash[n] += 1
           
        for k, v in nhash.items():
            if v == 1:
                return k
       
        return None

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 141 ms, faster than 85.70% of Python3 online submissions for Single Number.
Memory Usage: 16.7 MB, less than 84.62% of Python3 online submissions for Single Number.
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        res = 0
        for num in nums: res ^= num
        return res
        # return 2*sum(set(nums)) - sum(nums)

Coffee님의 댓글

  • 익명
  • 작성일
class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0; i<nums.length; i++){
            int num = map.getOrDefault(nums[i], 0);
            map.put(nums[i], num+1);
        }
        
        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            if(entry.getValue() == 1){
                result = entry.getKey();
            }
        }
        
        return result;
    }
}
전체 24 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


알림 0