540. Single Element in a Sorted Array
2018-01-13 21:34
405 查看
题目说,给出一串有序数组,每个数字重复两次,其中有个数字只出现一次,找出它。
想法很简单,因为每个数字都出现两次,那么用一个循环,检查偶数位的数字是否和后面的数字相同,不同则找到。代码如下:
class Solution {
public int singleNonDuplicate(int[] nums) {
for (int i = 0; i < nums.length - 1; i += 2) {
if (nums[i] != nums[i + 1]) return nums[i];
}
return nums[nums.length - 1];
}
}
想法很简单,因为每个数字都出现两次,那么用一个循环,检查偶数位的数字是否和后面的数字相同,不同则找到。代码如下:
class Solution {
public int singleNonDuplicate(int[] nums) {
for (int i = 0; i < nums.length - 1; i += 2) {
if (nums[i] != nums[i + 1]) return nums[i];
}
return nums[nums.length - 1];
}
}
相关文章推荐
- 540. Single Element in a Sorted Array
- 540. Single Element in a Sorted Array Difficulty:Medium
- leetcode 540. Single Element in a Sorted Array 题解
- 540. Single Element in a Sorted Array
- [LeetCode] 540. Single Element in a Sorted Array
- 【LeetCode】540. Single Element in a Sorted Array
- LeetCode - 540. Single Element in a Sorted Array
- [LeetCode]540. Single Element in a Sorted Array
- 540. Single Element in a Sorted Array
- 540. Single Element in a Sorted Array
- lettcode:540. Single Element in a Sorted Array(已排序数组中出现一次的数字,其他数字出现两次)
- 540. Single Element in a Sorted Array
- leetcode 540. Single Element in a Sorted Array
- 540. Single Element in a Sorted Array
- 540. Single Element in a Sorted Array
- 【LeetCode】540. Single Element in a Sorted Array 解题报告
- LeetCode 540. Single Element in a Sorted Array
- LeetCode 540. Single Element in a Sorted Array (Medium)
- LeetCode 540. Single Element in a Sorted Array
- leetcode 540. Single Element in a Sorted Array