码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Single Number

时间:2014-06-20 23:34:47      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   ext   

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?

Analysis: 需求里面要求O(N)时间以及无额外空间,这就排除了使用boolean array, hashmap这些个方法,只能在原数组上进行查找。O(N)基本上就相当于遍历数组,于是我就想怎么才能遍历一遍数组就知道哪个数是single的,于是就想到了需要sort一下这个数组,寻找前后元素不一样的项。

 1 public class Solution {
 2     public int singleNumber(int[] A) {
 3         java.util.Arrays.sort(A);
 4         if (A.length == 1) return A[0];
 5         int i = 1;
 6         while (i < A.length) {
 7             if (A[i] != A[i-1]) return A[i-1];
 8             i += 2;
 9         }
10         return A[i-1];
11     }
12 }

 

Leetcode: Single Number,布布扣,bubuko.com

Leetcode: Single Number

标签:style   class   blog   code   java   ext   

原文地址:http://www.cnblogs.com/EdwardLiu/p/3795723.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!