@@ -17,4 +17,82 @@ Output : 5
1717Minimum difference is between 1 and -4
1818
1919## 來源
20- * https://www.geeksforgeeks.org/find-minimum-difference-pair/
20+ * https://www.geeksforgeeks.org/find-minimum-difference-pair/
21+
22+ ## 解答
23+ https://github.com/kimi0230/LeetcodeGolang/blob/master/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/Find-Minimum-Difference-Between-Any-Two-Elements.go
24+
25+ ``` go
26+ package findminimumdifferencebetweenanytwoelements
27+
28+ import (
29+ " math"
30+ " sort"
31+ )
32+
33+ /*
34+ https://yourbasic.org/golang/absolute-value-int-float/
35+ http://cavaliercoder.com/blog/optimized-abs-for-int64-in-go.html
36+ fmt.Println(abs(math.MinInt64)) // Output: -9223372036854775808
37+
38+ // 似乎比較快
39+ func WithTwosComplement(n int64) int64 {
40+ y := n >> 63 // y ← x ⟫ 63
41+ return (n ^ y) - y // (x ⨁ y) - y
42+ }
43+ */
44+ func abs (n int ) int {
45+ if n < 0 {
46+ return -n
47+ }
48+ return n
49+ }
50+
51+ func WithTwosComplement (n int64 ) int64 {
52+ y := n >> 63 // y ← x ⟫ 63
53+ return (n ^ y) - y // (x ⨁ y) - y
54+ }
55+
56+ // O(n Log n)
57+ func FindMinDiff (nums []int ) int {
58+ if len (nums) <= 0 {
59+ return 0
60+ }
61+ sort.Ints (nums) // O(n Log n)
62+
63+ minSize := math.MaxInt32
64+
65+ // O(n)
66+ for i := 1 ; i < len (nums); i++ {
67+ tmp := int (math.Abs (float64 (nums[i] - nums[i-1 ])))
68+ if minSize > tmp {
69+ minSize = tmp
70+ }
71+ }
72+
73+ if minSize == math.MaxInt32 {
74+ minSize = 0
75+ }
76+ return minSize
77+ }
78+
79+ func FindMinDiff2 (nums []int ) int {
80+ if len (nums) <= 0 {
81+ return 0
82+ }
83+ sort.Ints (nums)
84+
85+ minSize := math.MaxInt32
86+ for i := 1 ; i < len (nums); i++ {
87+ tmp := abs (nums[i] - nums[i-1 ])
88+ if minSize > tmp {
89+ minSize = tmp
90+ }
91+ }
92+
93+ if minSize == math.MaxInt32 {
94+ minSize = 0
95+ }
96+ return minSize
97+ }
98+ ```
0 commit comments