File tree Expand file tree Collapse file tree 4 files changed +86
-0
lines changed
pullrequests/search_insert_position Expand file tree Collapse file tree 4 files changed +86
-0
lines changed Original file line number Diff line number Diff line change
1
+ //lint:file-ignore U1000 Ignore all unused code
2
+ package searchinsertposition
3
+
4
+ /*
5
+ 時間:12分
6
+ 解法自体はすぐに浮かんで解くことができた。
7
+ その割に二分探索を書くのがまだ慣れていなくて少し時間がかかってしまった。
8
+ */
9
+ func searchInsert_step1 (nums []int , target int ) int {
10
+ left , right := 0 , len (nums )
11
+ var mid int
12
+ for left < right {
13
+ mid = (left + right ) / 2
14
+ if target == nums [mid ] {
15
+ return mid
16
+ }
17
+ if target < nums [mid ] {
18
+ right = mid
19
+ } else {
20
+ left = mid + 1
21
+ }
22
+ }
23
+ if target < nums [mid ] {
24
+ return mid
25
+ }
26
+ return mid + 1
27
+ }
Original file line number Diff line number Diff line change
1
+ //lint:file-ignore U1000 Ignore all unused code
2
+ package searchinsertposition
3
+
4
+ /*
5
+ 最後の部分はleftを返せ馬良いと気づき変更した。
6
+ その他もより読みやすいように直した。
7
+ */
8
+ func searchInsert_step2 (nums []int , target int ) int {
9
+ left , right := 0 , len (nums )
10
+ for left < right {
11
+ mid := (left + right ) / 2
12
+ if nums [mid ] == target {
13
+ return mid
14
+ }
15
+ if nums [mid ] < target {
16
+ left = mid + 1
17
+ } else {
18
+ right = mid
19
+ }
20
+ }
21
+ return left
22
+ }
Original file line number Diff line number Diff line change
1
+ //lint:file-ignore U1000 Ignore all unused code
2
+ package searchinsertposition
3
+
4
+ /*
5
+ オーバーフローを起こさないようにmidの計算方法を修正した
6
+ https://github.com/hayashi-ay/leetcode/blob/064fca989bc4ecf9c7bce70237524a3e7ab1a21a/35.%20Search%20Insert%20Position.md?plain=1#L6
7
+ */
8
+ func searchInsert_step3 (nums []int , target int ) int {
9
+ left , right := 0 , len (nums )
10
+ for left < right {
11
+ mid := left + (right - left )/ 2
12
+ if nums [mid ] == target {
13
+ return mid
14
+ }
15
+ if nums [mid ] < target {
16
+ left = mid + 1
17
+ } else {
18
+ right = mid
19
+ }
20
+ }
21
+ return left
22
+ }
Original file line number Diff line number Diff line change
1
+ //lint:file-ignore U1000 Ignore all unused code
2
+ package searchinsertposition
3
+
4
+ func searchInsert (nums []int , target int ) int {
5
+ left , right := 0 , len (nums )
6
+ for left < right {
7
+ mid := left + (right - left )/ 2
8
+ if nums [mid ] < target {
9
+ left = mid + 1
10
+ } else {
11
+ right = mid
12
+ }
13
+ }
14
+ return left
15
+ }
You can’t perform that action at this time.
0 commit comments