A question LeeCode daily - a number appears only

  [Introduction] adhere day more LeeCode brush title series

    short step, a thousand miles; not small streams into a mighty torrent. We would like to encourage each other and gentlemen!


  [Title] 136. The number appears only once

    subject description: Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears twice. To find out that only appears once in the elements.

    说明:Your algorithm should have linear time complexity. You can not use the extra space to achieve it?


    Example:

		示例 1:
			输入: [2,2,1]
			输出: 1
 				  
		示例 2:
			输入: [4,1,2,1,2]
			输出: 4

    思路一:Although it is known Violence Act timeout error occurs, but according to someone senior said, often violence is the way we solve the most likely to think, and on this basis we can be better to think about how to improve the algorithm. So I realized a little way of solving violence.
         Ideas for 通过两个循环的遍历,来统计每个元素出现的次数, if greater than or equal to 2, then exits the loop; if it is equal to 1 and has traversed the last element, that value is returned. Specific code as follows:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==1:
            return nums[0]
        else:
            for i in range(len(nums)):
                count = 0   #这里设为0是因为在下面的比较过程中,也比较了自己本身那个元素
                for j in range(len(nums)):
                    if nums[i] == nums[j]:
                        count = count+1
                    if count>=2:  #大于等于2则跳出循环
                        break
                    elif count==1 and j == len(nums)-1:#等于1且遍历到了最后一个元素
                        return nums[i]

    Run Result: the 超时error, by way of two-cycle, the time complexity is O (n ^ 2), and therefore For long list, a timeout occurs the phenomenon.


    思路二:So how do we optimize it? ? ? We can think under the above practices Why do we need two cycles?
         I believe there is no problem of the above method can quickly answer a friend: the first cycle is through all elements of the second cycle in order to count.
         The next question becomes how do we reduce the two steps as much as possible, follow these steps:
           1. Using the dictionary approach to storage, because it can be done counting function when traversing
           2. With regard to count, because the topics given that only one appears once, all the other appears twice, so good, we just need to assign an already existing elements 2, does not exist in the dictionary of the element assigned to
           3. traversing the dictionary all the keys, the return value 1 for the index of
         the specific code as follows:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        hashmap = {}  #用于存储
        for index,num in enumerate(nums):
            if num not in hashmap:  #如果该元素未在hashmap中
                hashmap[num] = 1
            elif num in hashmap:   #如果该元素在hashmap中
                hashmap[num] = 2
        for i in list(dict.keys(hashmap)): #循环遍历hashmap的键
            if hashmap[i] ==1:
                return i

    operation result:
    Here Insert Picture Description

    思路三:Of course, we are also very easy to think of using the list function to count the number of statistics, specific code as follows:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in range(len(nums)):
            if nums.count(nums[i])==1:
                return nums[i]

    operation result:

    

    Some knowledge about the link:
    List COUNT method

    Share on here, welcome to discuss the exchange.


    注明

    Topic Source: stay button (LeetCode)
    link: https: //leetcode-cn.com/problems/single-number/

Published 32 original articles · won praise 62 · views 1296

Guess you like

Origin blog.csdn.net/Mingw_/article/details/104788018
Recommended