268. Missing Number
生活随笔
收集整理的這篇文章主要介紹了
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: 2Example 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; }轉載于:https://www.cnblogs.com/luozhiyun/p/8367149.html
總結
以上是生活随笔為你收集整理的268. Missing Number的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP之mb_internal_enco
- 下一篇: 48.结构体位域获取内存模型