博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode -- Single Number II
阅读量:7114 次
发布时间:2019-06-28

本文共 1907 字,大约阅读时间需要 6 分钟。

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?

[解题思路]

人生最悲催的事是刚面完试,leetcode就把我面试的题目给刷出来了。。。。

1.O(n) time complexity O(n) space complexity count the ocurrence of every number

1 public class Solution { 2     public int singleNumber(int[] A) { 3         // Note: The Solution object is instantiated only once and is reused by each test case. 4         int N = A.length; 5         if(N == 0){ 6             return N; 7         } 8          9         Map
counts = new HashMap
();10 for(int i = 0; i < N; i++){11 if(counts.containsKey(A[i])){12 counts.put(A[i], counts.get(A[i]) + 1);13 } else {14 counts.put(A[i], 1);15 }16 }17 18 Iterator
> iterator = counts.entrySet().iterator();19 while(iterator.hasNext()){20 Map.Entry
entry = iterator.next();21 if(entry.getValue() != 3){22 return entry.getKey();23 }24 }25 return 0;26 }27 }

 

 2.使用O(1)的空间来解决

1 public int singleNumber(int[] A) { 2         // Note: The Solution object is instantiated only once and is reused by each test case. 3         int N = A.length; 4         if(N == 0){ 5             return N; 6         } 7          8         int[] counts = new int[32]; 9         int result = 0;10         for(int i = 0; i < 32; i++){11             for(int j = 0; j < N; j++){12                 if(((A[j] >> i) & 1) == 1){13                     counts[i] = (counts[i] + 1) % 3;14                 }15             }16             result |= (counts[i] << i);17         }18         19         return result;20     }

ref:

转载地址:http://vyghl.baihongyu.com/

你可能感兴趣的文章
Xcode插件优缺点对比(推荐20款插件)
查看>>
IOS-面试题
查看>>
hdu 2055 An easy problem (java)
查看>>
HTML5本地存储——Web SQL Database
查看>>
[异常解决] JTAG 与STM32的SWD连接接线方式
查看>>
webstorm快捷键 webstorm keymap内置快捷键英文翻译、中英对照说明
查看>>
热修改 MySQL 数据库 pt-online-schema-change 的使用详解
查看>>
Android调试优化篇
查看>>
Linux技巧汇总
查看>>
EF框架step by step(8)—Code First DataAnnotations(2)
查看>>
MySQL 若干操作
查看>>
Apache Rewrite规则详解
查看>>
JSON 之JAVA 解析
查看>>
MVC5网站开发之一 总体概述
查看>>
windows编程之菜单操作
查看>>
关键路径法
查看>>
Java并发编程:线程和进程的创建(转)
查看>>
【转】如何利用logrotate工具自动切分滚动中的日志文件
查看>>
视频摘要视频浓缩
查看>>
wow.js使用方法
查看>>