您的位置:首页 > 编程语言 > Python开发

LeetCode Single Number III (Java和Python代码)

2015-10-13 17:06 579 查看
题目

[code]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。

代码:

[code]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版代码:

[code]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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: