• 268. Missing Number


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

    Example 1

    Input: [3,0,1]
    Output: 2
    
    

    Example 2

    Input: [9,6,4,2,3,5,7,0,1]
    Output: 8
    

    我的版本:

    package leetCode;
    
    import java.util.Arrays;
    
    /**
     * Created by luoluo on 2018/1/27.
     	先进行快排,然后在判断
     */
    public class MissingNumber {
    
        public static void main(String[] args) {
            int[] a = {3,0,1};
            missingNumber(a);
            System.out.println(Arrays.toString(a));
        }
    
        public static int missingNumber(int[] nums) {
            int n = nums.length;
    
            sort(nums, 0, n-1);
    
            if(nums[0] != n ){
                return n;
            }else if(nums[nums.length-1] !=0){
                return 0;
            }
            for (int i = 0; i < nums.length-1; i++) {
                if(nums[i]-nums[i+1]!=1){
                    return nums[i]-1;
                }
            }
            return 0;
        }
    
        public static void sort(int[] nums ,int bg,int end){
            if (bg >= end) {
                return;
            }
            int partition = partition(nums, bg, end);
            sort(nums, bg, partition - 1);
            sort(nums, partition + 1, end);
        }
    
        public static int partition(int[] nums,int bg, int end){
            int l = nums[bg];
    
            int j = bg;
            for (int i = bg+1; i <= end; i++) {
                if(nums[i]>l){
                    j++;
                    swap(nums, i, j);
                }
            }
            swap(nums, j, bg);
            return j;
        }
    
        public static void swap(int[] nums ,int a ,int b) {
            int temp = nums[a];
            nums[a] = nums[b];
            nums[b] = temp;
        }
    }
    
    

    大神的版本:

    public static int missingNumber(int[] nums) {
        int sum = nums.length;
        for (int i = 0; i < nums.length; i++)
            sum += i - nums[i];
        return sum;
    }
    
  • 相关阅读:
    BZOJ2301——莫比乌斯&&整除分块
    2019HDU多校第五场A fraction —— 辗转相除法|类欧几里得
    AKS素性检测
    2019牛客多校B generator 1——十进制快速幂
    BZOJ 3884——欧拉降幂和广义欧拉降幂
    libevent HTTP client 的实现
    google proto buffer安装和简单示例
    setenv LD_LIBRARY_PATH
    Centos6.4下安装protobuf及简单使用
    lrzsz
  • 原文地址:https://www.cnblogs.com/luozhiyun/p/8367149.html
Copyright © 2020-2023  润新知