number问题

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?

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].

时间: 2024-08-24 19:59:38

number问题的相关文章

Codeforces 124A - The number of positions

题目链接:http://codeforces.com/problemset/problem/124/A Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing b

17. Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae", &q

实现一个函数clone,使JavaScript中的5种主要的数据类型(包括Number、String、Object、Array、Boolean)进行值复制

实现一个函数clone,可以对JavaScript中的5种主要的数据类型(包括Number.String.Object.Array.Boolean)进行值复制. 1 /** 对象克隆 2 * 支持基本数据类型及对象 3 * 递归方法 */ 4 function clone(obj) { 5 var o; 6 switch (typeof obj) { 7 case "undefined": 8 break; 9 case "string": o = obj + &q

解决sqoop报错Invalid number; item = ITEM_UNICODE

报错栈: java.sql.SQLException: Invalid number; item = ITEM_UNICODE at com.intersys.jdbc.SysList.getInt(SysList.java:1735) at com.intersys.jdbc.CacheResultSet.getInt(CacheResultSet.java:247) at org.apache.sqoop.lib.JdbcWritableBridge.readInteger(JdbcWrit

1005 Number Sequence

Problem Description A number sequence is defined as follows: f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7. Given A, B, and n, you are to calculate the value of f(n). Input The input consists of multiple test cases. Each test case co

Minimum Inversion Number 【线段数】

Problem DescriptionThe inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy i < j and ai > aj. For a given sequence of numbers a1, a2, ..., an, if we move the first m >= 0 numbers to the end of

171. Excel Sheet Column Number

Excel Sheet Column Number Related to question Excel Sheet Column Title Given a column title as appear in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 static publi

hdu 5898 odd-even number 数位DP

odd-even number Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 716    Accepted Submission(s): 385 Problem Description For a number,if the length of continuous odd digits is even and the length

Leetcode 202. Happy Number

202. Happy Number Total Accepted: 78171 Total Submissions: 208635 Difficulty: Easy Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace t

hdu 1394 Minimum Inversion Number(这道题改日我要用线段树再做一次哟~)

Problem Description The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy i < j and ai > aj. For a given sequence of numbers a1, a2, ..., an, if we move the first m >= 0 numbers to the end of