Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

解法:从1到n求和,然后依次减去数组中各元素,所得即为缺失的数。

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?

解法:两个相同的数异或为0, 某个数与0异或结果即为该数。

Single Number II

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?

解法一:根据在特定位上为1的元素个数对3取余是否非零,逐位判断单数在特定位上是否为1。将3改为其他整数可将算法推广。

public class Solution {
public int singleNumber(int[] nums) {
if (nums.length == 0) {
return -1;
}
int result = 0;
for (int i = 0; i < 32; i++) {
int count = 0;
int d = 1 << i;
for (int j = 0; j < nums.length; j++) {
if ((nums[j] & d) != 0) {
count++;
}
}
if (count % 3 != 0) {
result |= d;
}
}
return result;
}
}

解法二:

可以使用掩码变量:

  1. ones    代表第i th 位只出现一次的掩码变量
  2. twos   代表第i th 位只出现两次次的掩码变量
  3. threes   代表第i th 位只出现三次的掩码变量

当第 i th 位出现3次时,就 ones   和 twos   的第 i th 位设置为0. 最终的答案就是 ones。

public class Solution {
public int singleNumber(int[] nums) {
if (nums.length == 0) {
return -1;
}
int ones = 0, twos = 0, threes = 0;
for (int i = 0; i < nums.length; i++) {
twos |= ones & nums[i];
ones ^= nums[i];
threes = ones & twos;
ones &= ~threes;
twos &= ~threes;
}
return ones;
}
}

Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

解法:先遍历数组进行异或,得到异或结果。然后找出异或结果的最低位,将最低位跟数组元素进行与运算,根据结果是否为零将数组分为两部分,而两个数分别分布在这两部分中。在每个部分内分别进行异或,即可得到两个数。

public class Solution {
public int[] singleNumber(int[] nums) {
if (nums.length == 0 || nums.length == 1) {
return null;
}
int xor = 0;
for (int i = 0; i < nums.length; i++) {
xor ^= nums[i];
}
int lowbit = xor & (-xor);
int rst1 = 0;
int rst2 = 0;
for (int i = 0; i < nums.length; i++) {
if ((nums[i] & lowbit) == 0) {
rst1 ^= nums[i];
} else {
rst2 ^= nums[i];
}
}
int[] result = {rst1, rst2};
return result;
}
}

Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

解法一:

public class Solution {
public int majorityElement(int[] num) {
if(num.length==1){
return num[0];
} Arrays.sort(num); int prev=num[0];
int count=1;
for(int i=1; i<num.length; i++){
if(num[i] == prev){
count++;
if(count > num.length/2) return num[i];
}else{
count=1;
prev = num[i];
}
} return 0;
}
}

解法二:

public int majorityElement(int[] num) {
if (num.length == 1) {
return num[0];
} Arrays.sort(num);
return num[num.length / 2];
}

解法三:

public int majorityElement(int[] nums) {
int result = 0, count = 0; for(int i = 0; i<nums.length; i++ ) {
if(count == 0){
result = nums[i];
count = 1;
}else if(result == nums[i]){
count++;
}else{
count--;
}
} return result;
}

Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

解法:设置两个选举数,经过一次遍历选出出现频率最大的两个数,再进行一次遍历判断它们的出现次数是否大于⌊ n/3 ⌋

public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<Integer>();
int r1 = 0;
int r2 = 0;
int count1 = 0;
int count2 = 0;
for (int i = 0; i < nums.length; i++) {
if (r1 == nums[i]) {
count1++;
} else if (r2 == nums[i]) {
count2++;
} else if (count1 == 0) {
r1 = nums[i];
count1 = 1;
} else if (count2 == 0) {
r2 = nums[i];
count2 = 1;
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == r1) {
count1++;
} else if (nums[i] == r2) {
count2++;
}
}
if (count1 > nums.length / 3) {
result.add(r1);
}
if (count2 > nums.length / 3) {
result.add(r2);
}
return result;
}
}

注意:选举过程中判断某个元素是否跟两个当前选举数相等和两个count数是否为零的先后顺序不能颠倒。

譬如改为:

        for (int i = 0; i < nums.length; i++) {
if (count1 == 0) {
r1 = nums[i];
count1 = 1;
} else if (r1 == nums[i]) {
count1++;
} else if (count2 == 0) {
r2 = nums[i];
count2 = 1;
} else if (r2 == nums[i]) {
count2++;
} else {
count1--;
count2--;
}
}

此段在leetcode上会通过,但是事实上当数组输入为[1,2,2,3,2,2,4,5,6,7]时,在eclipse中输出结果为[]。而正确结果应该为[2].

number问题的更多相关文章

  1. JavaScript Math和Number对象

    目录 1. Math 对象:数学对象,提供对数据的数学计算.如:获取绝对值.向上取整等.无构造函数,无法被初始化,只提供静态属性和方法. 2. Number 对象 :Js中提供数字的对象.包含整数.浮 ...

  2. Harmonic Number(调和级数+欧拉常数)

    题意:求f(n)=1/1+1/2+1/3+1/4-1/n   (1 ≤ n ≤ 108).,精确到10-8    (原题在文末) 知识点:      调和级数(即f(n))至今没有一个完全正确的公式, ...

  3. Java 特定规则排序-LeetCode 179 Largest Number

    Given a list of non negative integers, arrange them such that they form the largest number. For exam ...

  4. Eclipse "Unable to install breakpoint due to missing line number attributes..."

    Eclipse 无法找到 该 断点,原因是编译时,字节码改变了,导致eclipse无法读取对应的行了 1.ANT编译的class Eclipse不认,因为eclipse也会编译class.怎么让它们统 ...

  5. 移除HTML5 input在type="number"时的上下小箭头

    /*移除HTML5 input在type="number"时的上下小箭头*/ input::-webkit-outer-spin-button, input::-webkit-in ...

  6. iOS---The maximum number of apps for free development profiles has been reached.

    真机调试免费App ID出现的问题The maximum number of apps for free development profiles has been reached.免费应用程序调试最 ...

  7. 有理数的稠密性(The rational points are dense on the number axis.)

    每一个实数都能用有理数去逼近到任意精确的程度,这就是有理数的稠密性.The rational points are dense on the number axis.

  8. [LeetCode] Minimum Number of Arrows to Burst Balloons 最少数量的箭引爆气球

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  9. [LeetCode] Number of Boomerangs 回旋镖的数量

    Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of po ...

  10. [LeetCode] Number of Segments in a String 字符串中的分段数量

    Count the number of segments in a string, where a segment is defined to be a contiguous sequence of ...

随机推荐

  1. Python sphinx-build在Windows系统中生成Html文档

    看到前同事发布的“Markdown/reST 文档发布流水线”基于TFS.Docker.Azure等工具和平台进行文档发布的介绍说明,不得不在心中暗暗竖起大拇指.这套模式,实现了文档编写后版本管理.发 ...

  2. 利用AForge.NET 调用电脑摄像头进行拍照

    当然了,你需要去官网下载类库,http://www.aforgenet.com/ 调用本机摄像头常用的组件: AForge AForge.Controls AForge.Imaging AForge. ...

  3. php与微信基础的学习

    我们要搞的是用php来与微信进行信息交互,现在是一个学习过程...结合慕课网渔夫老师的讲解. 微信公众号的申请具体可百度,太简单不予说明,微信本身功能也挺多,也有相关第三方平台,然而我们学习编程--具 ...

  4. 阿里云服务器 发送邮箱 STMP 25端口 465端口问题 Javamail 25被禁用

    我们传统使用的比较简单的是 STMP 25端口收发邮件 今天发现刚购买的阿里云服务器不能作为客户端通过STMP 25端口发送邮件 开始在网上有说发现是JDK1.8的原因,然后自己也把JDK1.8换到了 ...

  5. MongoDB【第二篇】集群搭建

    第一步:准备 1.安装包 mongodb-linux-x86_64-rhel70-3.4.2.tgz 2. 架构: 本文为 1-primary.1-secondary.1-arbiter 的 mong ...

  6. linux CentOS 权限问题修复(chmod 777 -R 或者chmod 755 -R问题修复)

    我个人曾经有一次经历: 就是在修改文件夹权限的时候,本来该执行: #chmod 777 -R ./ 结果我漏掉了那个".";执行的命令是chmod 777 -R /. 这个命令一定 ...

  7. html5 离线存储 地理信息与本地存储

    搭建离线应用程序 ①服务器设置头信息 : AddType text/cache-manifest .manifest ② html标签加 : manifest=“xxxxx.manifest” ③写m ...

  8. 《深入理解Java虚拟机》学习笔记之工具

    善于利用工具,不仅可以加快我们分析数据,还可以快速定位和解决问题.现在我们就来看看虚拟机性能监控和故障处理工具. 在JDK的bin目录可以看到sun免费送给了我们很多小工具,这些工具虽然小巧但功能强大 ...

  9. WebApi接口请求失败,找不到资源。

    WebApi开发接口,实现同步数据库的数据给安卓. public class UserInfoController : ApiControllerBase { private UserBLL user ...

  10. mongoDB & Nodejs 访问mongoDB (一)

    最近的毕设需要用到mongoDB数据库,又把它拿出来再学一学,下盘并不是很稳,所以做一些笔记,不然又忘啦. 安装 mongoDB & mongoVUE mongoDB: https://www ...