Leetcode (一)
来源:互联网 发布:毕业找不到工作知乎 编辑:程序博客网 时间:2024/04/30 00:32
Q1 Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
NOTE: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Solution 1:
这是leetcode提交成功率最高的也是最简单的一道题。最直观的作法,不考虑其对without using extra memory的限制,我们可以用一边遍历数组一边将遍历过的数字存储下来。如果这个数字之前已经遍历过了,就将他移除。这样,遍历完一遍后,剩下的一个元素,就是只出现过一次的元素了。
这样的数据结构,我们可以使用HashSet(或者HashMap)来存储遍历过的元素。如果这个元素之前出现过,就把他从set中删除。最后返回剩下的唯一的元素。
public int singleNumber(int[] A) { if (A == null || A.length == 0) return -1; HashSet<Integer> set = new HashSet<Integer>(); for (int i=0; i<A.length; i++) { if (set.contains(A[i])) { set.remove(A[i]); } else { set.add(A[i]); } } return (Integer)set.toArray()[0]; }
这样的时间复杂度是O(n),空间复杂度同样是O(n)。并且不符合without extra memory的要求。
Solution 2:
当看到两个相同的数字时,应该反应到,他们的异或(XOR, exclusive or, ^) 值为0。
x ^ x = 0, x ^ 0 = x
这样就提供了第二个解法,使用XOR计算所有的元素。出现两次的数字将XOR为0,这样只出现一次的数字就是所有元素XOR后的结果。
public int singleNumber(int[] A) { if (A == null || A.length == 0) { return -1; } int result = A[0]; for (int i=1; i<A.length; i++) { result ^= A[i]; } return result; }
这两种方法都能通过leetcode的检测,但显然第二种才是符合要求的。
0 0
- Leetcode (一)
- Leetcode Problem 汇总一
- leetcode每日一题
- Leetcode旅途一
- leetcode题解一
- Leetcode medium (一)
- leetcode思路一
- LeetCode题解(一)
- leetcode最后一遍
- LeetCode 笔记(一)
- leetcode数组(一)
- LeetCode字符串(一)
- Leetcode每日一练习
- leetcode刷刷刷(一)
- LeetCode-Java (一)
- LeetCode 之 string字符串一
- LeetCode 实现题(一)
- [LeetCode] 刷题笔记(一)
- C++primer14章习题
- Vacation is coming. No update fora while
- C++primer15章总结
- C++primer15章习题
- 水编译的两天
- Leetcode (一)
- 被问到的问题
- Hashmat the brave warrior
- Back to High School Physics
- Ecological Premium
- The Decoder
- Kindergarten Counting Game
- Machined Surfaces
- Rotating Sentences