zoukankan      html  css  js  c++  java
  • 136. Single Number

    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 ago Accepted 36 ms python
    2 minutes ago Accepted 1 ms java
    5 minutes ago Accepted 12 ms cpp
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    数据库 Mysql事务详解
    数据库 Mysql内容补充二
    数据库 Mysql内容补充一
    优化Django ORM中的性能问题(含prefetch_related 和 select_related)
    django高级
    百度,谷歌,360,搜狗,神马等蜘蛛IP段
    中国电信、联通、移动、教育IP分布
    sed 给文件每行末尾追加相同字符
    centos7 lvs keepalived做DNS集群负载
    Notepad++ 删除空白行的方法
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9960655.html
Copyright © 2011-2022 走看看