Skip to content

Commit

Permalink
#35 solve with both TypeScript and Golang
Browse files Browse the repository at this point in the history
  • Loading branch information
yukisato committed Jan 15, 2020
1 parent 986f5ae commit fb8e053
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 0 deletions.
22 changes: 22 additions & 0 deletions leetcode/solutions/0035.SearchInsertPosition/searchInsert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package solution

func searchInsert(nums []int, target int) int {
l := 0
r := len(nums) - 1

for l <= r {
mid := (l + r) / 2

if nums[mid] == target {
return mid
}

if nums[mid] < target {
l = mid + 1
} else {
r = mid - 1
}
}

return l
}
20 changes: 20 additions & 0 deletions leetcode/solutions/0035.SearchInsertPosition/searchInsert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export default function searchInsert(nums: number[], target: number): number {
let l = 0;
let r = nums.length - 1;

while (l <= r) {
const mid = (l + r) >>> 1;

if (nums[mid] === target) {
return mid;
}

if (nums[mid] < target) {
l = mid + 1;
} else {
r = mid - 1;
}
}

return l;
}
34 changes: 34 additions & 0 deletions leetcode/solutions/0035.SearchInsertPosition/searchInsert_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package solution

import "testing"

func Test_0035_SearchInsertPosition(t *testing.T) {
result := searchInsert([]int{1, 3, 5, 6}, 5)
expected := 2

if result != expected {
t.Errorf("TEST FAILED! got: %#v, want: %#v.", result, expected)
}

result = searchInsert([]int{1, 3, 5, 6}, 2)
expected = 1

if result != expected {
t.Errorf("TEST FAILED! got: %#v, want: %#v.", result, expected)
}

result = searchInsert([]int{1, 3, 5, 6}, 7)
expected = 4

if result != expected {
t.Errorf("TEST FAILED! got: %#v, want: %#v.", result, expected)
}

result = searchInsert([]int{1, 3, 5, 6}, 0)
expected = 0

if result != expected {
t.Errorf("TEST FAILED! got: %#v, want: %#v.", result, expected)
}

}
10 changes: 10 additions & 0 deletions leetcode/solutions/0035.SearchInsertPosition/searchInsert_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { test } from "https://deno.land/std/testing/mod.ts";
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
import searchInsert from "./searchInsert.ts";

test("0035. Search Insert Position", () => {
assertEquals(searchInsert([1, 3, 5, 6], 5), 2);
assertEquals(searchInsert([1, 3, 5, 6], 2), 1);
assertEquals(searchInsert([1, 3, 5, 6], 7), 4);
assertEquals(searchInsert([1, 3, 5, 6], 0), 0);
});

0 comments on commit fb8e053

Please sign in to comment.