victory的博客

长安一片月,万户捣衣声

0%

leetcode | 136.只出现一次的数字

136.只出现一次的数字

题目描述

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

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

题目链接

思路

  1. python版本
    遍历nums数组中的每一个数num,并使用list.count(num)统计num在nums中出现的次数,如果次数为1,返回num。
  2. java版本
    遍历nums数组中的每一个数num,使用HashMap记录每个num出现的次数,然后返回出现次数为1的num。

    代码

  3. python代码
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for num in nums:
            if nums.count(num) == 1:
                return num


if __name__ == "__main__":
    slt = Solution()
    nums = [2, 2, 1]
    result = slt.singleNumber(nums)
    print(result)
  1. java代码
import java.util.*;
class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int num : nums){
            if(map.get(num) == null){
                map.put(num, 1);
            }else{
                map.put(num, map.get(num)+1);
            }
        }
        
        for(int key: map.keySet()){
            if(map.get(key)==1){
                return key;
            }
        }
        return -1;
    }
}