From e14fb76097d117785c0a3af852eaff7d5a174966 Mon Sep 17 00:00:00 2001 From: Junqiao Date: Sun, 24 Sep 2023 10:43:51 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Update=200035.=E6=90=9C=E7=B4=A2=E6=8F=92?= =?UTF-8?q?=E5=85=A5=E4=BD=8D=E7=BD=AE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0035.搜索插入位置.md | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 04dd0cac..80b7e40e 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -258,6 +258,37 @@ public int searchInsert(int[] nums, int target) { +### C# + +```go +public int SearchInsert(int[] nums, int target) { + + var left = 0; + var right = nums.Length - 1; + + while (left <= right) { + + var curr = (left + right) / 2; + + if (nums[curr] == target) + { + return curr; + } + + if (target > nums[curr]) { + left = curr + 1; + } + else { + right = curr - 1; + } + } + + return left; +} +``` + + + ### Golang ```go @@ -500,3 +531,4 @@ int searchInsert(int* nums, int numsSize, int target){ + From 949dd979f7ca88a12a9b364b38e4da2457b27691 Mon Sep 17 00:00:00 2001 From: Junqiao Date: Sun, 24 Sep 2023 11:43:43 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=200034.=E5=9C=A8=E6=8E=92=E5=BA=8F?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E4=B8=AD=E6=9F=A5=E6=89=BE=E5=85=83=E7=B4=A0?= =?UTF-8?q?=E7=9A=84=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=92=8C=E6=9C=80=E5=90=8E?= =?UTF-8?q?=E4=B8=80=E4=B8=AA=E4=BD=8D=E7=BD=AE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...元素的第一个和最后一个位置.md | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md index b4128166..3bf90e3b 100644 --- a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md +++ b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md @@ -329,6 +329,67 @@ class Solution { } ``` +### C# + +```c# +public int[] SearchRange(int[] nums, int target) { + + var leftBorder = GetLeftBorder(nums, target); + var rightBorder = GetRightBorder(nums, target); + + if (leftBorder == -2 || rightBorder == -2) { + return new int[] {-1, -1}; + } + + if (rightBorder - leftBorder >=2) { + return new int[] {leftBorder + 1, rightBorder - 1}; + } + + return new int[] {-1, -1}; + +} + +public int GetLeftBorder(int[] nums, int target){ + var left = 0; + var right = nums.Length - 1; + var leftBorder = -2; + + while (left <= right) { + var mid = (left + right) / 2; + + if (target <= nums[mid]) { + right = mid - 1; + leftBorder = right; + } + else { + left = mid + 1; + } + } + + return leftBorder; +} + +public int GetRightBorder(int[] nums, int target){ + var left = 0; + var right = nums.Length - 1; + var rightBorder = -2; + + while (left <= right) { + var mid = (left + right) / 2; + + if (target >= nums[mid]) { + left = mid + 1; + rightBorder = left; + } + else { + right = mid - 1; + } + } + + return rightBorder; +} +``` + ### Python