本文主要是介绍[LeetCode] 136--Single Number --Medium--,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
今天又来做题了,因为Find the Duplicate Number一直没想出来,但又不想直接上网看答案,只好做与它类似的题目。
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?
Hide Tags Hash Table Bit Manipulation
Hide Similar Problems (M) Single Number II (M) Single Number III (M) Missing Number (H) Find the Duplicate Number
原题链接:https://leetcode.com/problems/single-number/
大概意思是:给出一个整型数组,找出没有重复的那一个数字。
要求,1时间效率是线性的;2能否实现不利用额外存储空间?
解法一:虽然说要求时间效率是线性,但是想试一下先排序后查找的方法,时间效率O(nlogn)。
*这里需要注意的是排序后的最后一个数字。
public class Solution {public int singleNumber(int[] nums) {if (nums == null) {return 0;}if (nums.length == 1) {return nums[0];}Arrays.sort(nums);for (int i = 0; i < nums.length - 1; i++) {if (0 == i % 2 && nums[i] != nums[i + 1]) {return nums[i];}}return nums[nums.length - 1];}
}
解法二:利用map,时间效率接近O(n)。
public class Solution {public int singleNumber(int[] nums) {if (nums == null) {return 0;}if (nums.length == 1) {return nums[0];}HashMap<Integer, Integer> numMap = new HashMap<>();for (int i = 0; i < nums.length; i++) {int sizeBefore = numMap.size();numMap.put(nums[i], nums[i]);int sizeAfter = numMap.size();if (sizeBefore == sizeAfter) {numMap.remove(nums[i]);}}return (int) numMap.entrySet().iterator().next().getValue();}
}
解法二:利用异或操作,时间效率O(n)。这个真的想不出来。
解法的原链接:https://leetcode.com/discuss/6170/my-o-n-solution-using-xor?show=28023#c28023
原理是异或操作满足交换律:
array is {2,1,4,5,2,4,1} then it will be like we are performing this operation,
((2^2)^(1^1)^(4^4)^(5)) => (0^0^0^5) => 5.
int singleNumber(int A[], int n) {int result = 0;for (int i = 0; i<n; i++){result ^=A[i];}return result;
}
这篇关于[LeetCode] 136--Single Number --Medium--的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!