LeetCode Single Number III (Java和Python代码)
2015-10-13 17:06
579 查看
题目
分析:
给定一个数组,数组中有两种元素一种是在数组中出现一次,一种是在数组中出现两次。写一个函数,找出给定数组中所有只出现一次的元素,并将这些元素放到一个数组中返回。
我们采用Java中HashMap结构,每次遇到新元素就向哈希表添加Key,并设定对应的值为1,如果该元素再次出现,设定值自增。
而后遍历哈希表中所有的key和对应的value,如果value是1,则在返回的数组中添加对应的key。
代码:
以上是Java版本的代码,同时提供Python版本的代码,由于Python间洁的特性和自带数据类型中包含了字典,相对来说Python版本的代码比较间洁。
以下是Python版代码:
[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
相关文章推荐
- python学习006--字符串操作
- python 日期加减
- python3中django无法展示数据库表内容的解决方法
- python多线程编程(二)--threading模块
- python多线程编程(一)--thread模块
- opencv无法读取视频解决方法&&抽取视频帧存储为图像(python)
- python学习005--数学函数
- 老李分享:pep8 python代码规范
- 【python】:python学习笔记
- python爬虫抽取武侠小说
- 老李分享:使用 Python 的 Socket 模块开发 UDP 扫描工具
- python学习004--Python运算符优先级
- Python输出中文到文件时的字符编码问题
- Python时间戳和日期
- python学习03--格式化输出
- Python中的并发编程
- Python 使用thrift连接hbase || 远程连接hbase
- python自动化执行脚本
- 搭建Python开发环境
- python学习002