LeetCode:34. Search for a Range(Medium)

1. 原题链接

https://leetcode.com/problems/search-for-a-range/description/

2. 题目要求

给定一个按升序排列的整型数组nums[ ]和目标值target(int类型),如果数组中存在目标值,返回目标值在数组中的起始位置和结束位置,[start, end]。不存在返回 [-1, -1]。

3. 解题思路

思路一:暴力解决,遍历数组进行匹配,时间复杂度O( n )

4. 代码实现

 1 package com.huiAlex;
 2 
 3 public class SearchForARange34 {
 4     public static void main(String[] args) {
 5         int[] nums = {5, 7, 7, 8, 8, 8, 8, 10};
 6         int[] res = searchRange(nums, 8);
 7         for (int x : res)
 8             System.out.println(x);
 9     }
10 
11     public static int[] searchRange(int[] nums, int target) {
12         int start, end, count;
13         start = 0;
14         end = 0;
15         count = 0;
16         for (int i = 0; i < nums.length; i++) {
17             if (nums[i] == target) {
18                 start = i;
19                 count++;
20             }
21             if (nums[i] > target) break;
22         }
23 
24         if (count == 0) {
25             start = -1;
26             end = -1;
27         } else {
28             end = start;
29             start -= count - 1;
30         }
31         return new int[]{start, end};
32     }
33 }

 

posted @ 2018-01-05 10:41  一只敲码的猫  阅读(167)  评论(0编辑  收藏  举报