136. Single Number

本文介绍了一种在整数数组中找出唯一出现一次元素的算法,该算法具备线性时间复杂度,并提供了C++、Java和Python三种实现方式。文章强调了算法的高效性和内存使用优化,通过示例展示了算法的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

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

Example 2:

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

Approach #1: C++.

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        unordered_map<int, int> mp;
        for (int i = 0; i < nums.size(); ++i) 
            mp[nums[i]]++;
        for (int i = 0; i < nums.size(); ++i)
            if (mp[nums[i]] == 1) return nums[i];
    }
};

  

Approach #2: Java.

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for (int i : nums)
            result ^= i;
        return result;
    }
}

Note: ^ return 0 if two elements is same.

 

Approach #3: Python.

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dic = {}
        for num in nums:
            dic[num] = dic.get(num, 0) + 1
        for key, val in dic.items():
            if val == 1:
                return key

The dictionary get method:

Description

The method get() returns a value for the given key. If key is not available then returns default value None.

Syntax

Following is the syntax for get() method −

dict.get(key, default = None)

Parameters

  • key − This is the Key to be searched in the dictionary.

  • default − This is the Value to be returned in case key does not exist.

Return Value

This method return a value for the given key. If key is not available, then returns default value None.

 

Time SubmittedStatusRuntimeLanguage
a few seconds agoAccepted36 mspython
2 minutes agoAccepted1 msjava
5 minutes agoAccepted12 mscpp

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/9960655.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值