From cded4a22b78674a8fee28b5c0363a743e44ccf56 Mon Sep 17 00:00:00 2001 From: yuanguangxin <274841922@qq.com> Date: Thu, 26 Mar 2020 21:48:04 +0800 Subject: [PATCH] add q34 --- .idea/workspace.xml | 95 ++++++++----------- README.md | 1 + .../Solution.java | 60 ++++++++++++ 3 files changed, 102 insertions(+), 54 deletions(-) create mode 100644 src/分治法/q34_在排序数组中查找元素的第一个和最后一个位置/Solution.java diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 3fb544b..73d0dc3 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,7 +2,7 @@ - + @@ -80,13 +80,13 @@ - - - @@ -675,7 +662,6 @@ - @@ -700,7 +686,8 @@ - @@ -715,55 +702,55 @@ - + - + - + - - - + + + - - - + + + - - - + + + - - - + + + - + - + - + - + - + - + - + @@ -773,10 +760,10 @@ - + - + diff --git a/README.md b/README.md index a80a1f7..3431465 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ * [q23_合并K个排序链表](/src/分治法/q23_合并K个排序链表) * [q33_搜索旋转排序数组](/src/分治法/q33_搜索旋转排序数组) +* [q34_在排序数组中查找元素的第一个和最后一个位置](/src/分治法/q34_在排序数组中查找元素的第一个和最后一个位置) ### 动态规划 diff --git a/src/分治法/q34_在排序数组中查找元素的第一个和最后一个位置/Solution.java b/src/分治法/q34_在排序数组中查找元素的第一个和最后一个位置/Solution.java new file mode 100644 index 0000000..daf19d6 --- /dev/null +++ b/src/分治法/q34_在排序数组中查找元素的第一个和最后一个位置/Solution.java @@ -0,0 +1,60 @@ +package 分治法.q34_在排序数组中查找元素的第一个和最后一个位置; + +/** + * 二分法 o(log(n)) + */ +public class Solution { + + public int[] searchRange(int[] nums, int target) { + if (nums == null || nums.length < 1) { + return new int[]{-1, -1}; + } + int midIndex = find(0, nums.length - 1, nums, target); + int[] rs = new int[2]; + rs[0] = midIndex; + rs[1] = midIndex; + if (midIndex == -1) { + return rs; + } + while (nums[rs[0]] == target && rs[0] > 0) { + int temp = find(0, rs[0] - 1, nums, target); + if (temp == -1) { + break; + } else { + rs[0] = temp; + } + } + + while (nums[rs[1]] == target && rs[1] < nums.length - 1) { + int temp = find(rs[1] + 1, nums.length - 1, nums, target); + if (temp == -1) { + break; + } else { + rs[1] = temp; + } + } + return rs; + } + + public int find(int beginIndex, int endIndex, int[] nums, int target) { + if (beginIndex == endIndex) { + if (nums[beginIndex] == target) { + return beginIndex; + } else { + return -1; + } + } + int mid = (endIndex - beginIndex) / 2 + beginIndex; + if (nums[mid] > target) { + return find(beginIndex, mid, nums, target); + } else if (nums[mid] < target) { + return find(mid + 1, endIndex, nums, target); + } else { + return mid; + } + } + + public static void main(String[] args) { + new Solution().searchRange(new int[]{2, 2}, 2); + } +}