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)
  • 相关阅读:
    String
    Array常用方法
    Array类
    ruby调试/练习时的小技巧
    集合类对象的遍历处理办法
    Tech road one step 7-Noc to 13-Nov
    Tech road one step 31-Oct 6-Nov
    TechRoad_oneStep_17-23 10
    TechRoad_oneStep_1001
    TechRoad_oneStep_0919
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9960655.html
Copyright © 2011-2022 走看看