Bläddra i källkod

add 0~n-1中缺失的数字

tangs 2 år sedan
förälder
incheckning
baa2c66881
1 ändrade filer med 48 tillägg och 0 borttagningar
  1. 48 0
      leetcode/剑指offer/0~n-1中缺失的数字/main.go

+ 48 - 0
leetcode/剑指offer/0~n-1中缺失的数字/main.go

@@ -0,0 +1,48 @@
+package main
+
+import (
+	"bufio"
+	"fmt"
+	"os"
+	"strconv"
+	"strings"
+)
+
+func main() {
+	var input = bufio.NewScanner(os.Stdin)
+	var output int
+	var digits []int
+	for input.Scan() {
+		line := input.Text()
+
+		digits = []int{}
+		values := strings.Split(line, " ")
+
+		for _, v := range values {
+			d, _ := strconv.Atoi(v)
+			digits = append(digits, d)
+		}
+
+		output = missingNumber(digits)
+		fmt.Println(output)
+	}
+}
+
+func missingNumber(nums []int) int {
+	var length = len(nums)
+	if length-1 == nums[length-1] {
+		return length
+	}
+	var left, right = 0, len(nums) - 1
+	var mid int
+	for left < right {
+		mid = (left + right) / 2
+		if nums[mid] > mid {
+			right = mid
+		} else {
+			left = mid + 1
+		}
+	}
+
+	return left
+}