From de52857387cd8f72494f972439211dba77bf0593 Mon Sep 17 00:00:00 2001 From: Openset Date: Fri, 11 Jan 2019 10:50:05 +0800 Subject: [PATCH 1/2] Add: Monotonic Array --- problems/monotonic-array/monotonic_array.go | 12 ++++++ .../monotonic-array/monotonic_array_test.go | 42 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/problems/monotonic-array/monotonic_array.go b/problems/monotonic-array/monotonic_array.go index bc9bae6e1..1c5204e03 100644 --- a/problems/monotonic-array/monotonic_array.go +++ b/problems/monotonic-array/monotonic_array.go @@ -1 +1,13 @@ package monotonic_array + +func isMonotonic(A []int) bool { + t, f := 0, 0 + for i, v := range A[1:] { + if v > A[i] { + t++ + } else if v < A[i] { + f++ + } + } + return t == 0 || f == 0 +} diff --git a/problems/monotonic-array/monotonic_array_test.go b/problems/monotonic-array/monotonic_array_test.go index bc9bae6e1..16a609a8a 100644 --- a/problems/monotonic-array/monotonic_array_test.go +++ b/problems/monotonic-array/monotonic_array_test.go @@ -1 +1,43 @@ package monotonic_array + +import "testing" + +type caseType struct { + input []int + expected bool +} + +func TestIsMonotonic(t *testing.T) { + tests := [...]caseType{ + { + input: []int{1, 2, 2, 3}, + expected: true, + }, + { + input: []int{6, 5, 4, 4}, + expected: true, + }, + { + input: []int{1, 3, 2}, + expected: false, + }, + { + input: []int{1, 2, 4, 5}, + expected: true, + }, + { + input: []int{1, 1, 1}, + expected: true, + }, + { + input: []int{1, 2, 3, 3, 3, 2, 1}, + expected: false, + }, + } + for _, tc := range tests { + output := isMonotonic(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +} From 5a203568f85a831f9509ac0638e7678a685cab97 Mon Sep 17 00:00:00 2001 From: Openset Date: Fri, 11 Jan 2019 11:00:28 +0800 Subject: [PATCH 2/2] Update: Monotonic Array --- problems/monotonic-array/monotonic_array.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/problems/monotonic-array/monotonic_array.go b/problems/monotonic-array/monotonic_array.go index 1c5204e03..457484c26 100644 --- a/problems/monotonic-array/monotonic_array.go +++ b/problems/monotonic-array/monotonic_array.go @@ -1,13 +1,13 @@ package monotonic_array func isMonotonic(A []int) bool { - t, f := 0, 0 + increasing, decreasing := true, true for i, v := range A[1:] { if v > A[i] { - t++ + decreasing = false } else if v < A[i] { - f++ + increasing = false } } - return t == 0 || f == 0 + return increasing || decreasing }