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

Leetcode: Single Number II

时间:2014-06-28 13:44:09      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:style   blog   java   color   cti   for   

Given an array of integers, every element appears three times 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: 注意那个single one的个数可能比3少,也可能比3多。所以想法就是先sorting,然后从小到大遍历每个元素,前后元素相同时counter++,不相同时看counter是否为3,不是的话就返回前一个元素,是的话counter重新置1.  特殊情况在于single one在最后,所以如果循环执行完了函数都还没有return,说明single one是最后的元素。要注意,对于这种需要返回值的function, 不能所有的return都在if语句里

 1 public class Solution {
 2     public int singleNumber(int[] A) {
 3         java.util.Arrays.sort(A);
 4         int count = 1;
 5         int i;
 6         for (i = 1; i < A.length; i++) {
 7             if (A[i] == A[i-1]) {
 8                 count++;
 9             }
10             else {
11                 if (count != 3) return A[i-1];
12                 count = 1;
13             }
14         }
15         return A[i-1];
16     }
17 }

 

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

Leetcode: Single Number II

标签:style   blog   java   color   cti   for   

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

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