LeetCode Single Number III (Java和Python代码)

题目

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

分析:

给定一个数组,数组中有两种元素一种是在数组中出现一次,一种是在数组中出现两次。写一个函数,找出给定数组中所有只出现一次的元素,并将这些元素放到一个数组中返回。

我们采用Java中HashMap结构,每次遇到新元素就向哈希表添加Key,并设定对应的值为1,如果该元素再次出现,设定值自增。

而后遍历哈希表中所有的key和对应的value,如果value是1,则在返回的数组中添加对应的key。

代码:

public class Solution {
    public int[] singleNumber(int[] nums) {
        ArrayList<Integer> list = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0;i < nums.length;i++)
        {
            if(map.containsKey(nums[i]))
                map.put(nums[i], map.get(nums[i])+1);
            else
                map.put(nums[i], 1);
        }
        for(Entry<Integer, Integer> entry:map.entrySet())
        {
            if(entry.getValue() == 1)
                list.add(entry.getKey());
        }
        int []res = new int[list.size()];
        for(int i = 0 ;i < list.size();i++)
        {
            res[i] = list.get(i);
        }
        return res;

    }
}

以上是Java版本的代码,同时提供Python版本的代码,由于Python间洁的特性和自带数据类型中包含了字典,相对来说Python版本的代码比较间洁。
以下是Python版代码:

def singleNumber(nums):
    """
    :type nums: List[int]
    :rtype: List[int]
    """
    tmpdict = {}
    res = []
    for i in nums:
        if i in tmpdict:
            tmpdict[i] += 1;
        else:
            tmpdict[i] = 1
    for key, val in tmpdict:
        if val is 1:
            res.append(key)
    return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值