LeetCode解题报告--Search for a Range

题目:

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,

Given [5, 7, 7, 8, 8, 10] and target value 8,

return [3, 4].

点击解题:Search for a Range

分析:题意要求找目标数组在出已排序数列的范围。

题目难度不大,注意时间复杂度O(logn),是该题的关键,三种解题思路:

1)暴力法直接遍历(超时):直接用for循环从左到右遍历,时间复杂度为O(n),超时。先找记录第一次nums[i] = target,array[0] = i,之后继续遍历,直至nums[i] != target,array[1] = i。

2)二分查找法(可行):先找到nums[i] == target,不管i是左边界还是右边界,或是中间值,即找到第一个nums[i] = target, 之后在找到的i基础上,向右遍历找到右边界,向左遍历,找到左边界。注意当找到第一个i =0 (或 i = nums.length - 1),则左(或右)边界找到,只需找右(或左)边界,加个判断。

3)双指针发(可行):双指针left和right分别指向数组的起始,即left = 0,right = nums.length - 1,之后,先从左向右遍历,找到第一个nums[i] = target,left = i, 此时left为左边界;接着再从右向左遍历,找到第一个nums[i] = target,right = i,此时right为右边界。

如下示意图示:

Java代码:Accepted

Binary Search:

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        //term, termq for termporary variable, save the first middle
        int tem = 0;
        int tem1 = 0;
        //sign whether find target
        int flag = 0;
        int[] array = new int[] { -1, -1 };

        //Binary search to find first middle nums[middle] = target
        while (left <= right) {
            int middle = (left + right) / 2;
            if (nums[middle] == target) {
                tem = middle;
                tem1 = middle;
                flag = 1;
                break;
            } else if (nums[middle] < target) {
                left = middle + 1;
            } else {
                right = middle - 1;
            }
        }

        //if not return[-1,-1]
        if (flag == 0) {
            return array;
        }

        //find the right boundary
        if(tem != nums.length - 1){
            while (tem < nums.length) {
                if ((tem + 1 < nums.length) && nums[tem] == nums[tem + 1]) {
                    tem++;
                } else {
                    array[1] = tem;
                    break;
                }
            }
        }else{
            array[1] = tem;
        }

        //find left boundary
        if(tem1 != 0){
            while (tem1 > -1) {
                if ((tem1 - 1 > -1) && nums[tem1] == nums[tem1 - 1]) {
                    tem1--;
                } else {
                    array[0] = tem1;
                    break;
                }
            }
        }else{
            array[0] = tem1;
        }

        return array;
    }
}

Tow Points Search:

public class Solution {
    public int[] searchRange(int[] nums, int target) {

        int[] array = new int[]{-1,-1};

        //tow points for search nums[left] == target and nums[right] == target
        int left = 0;
        int right = nums.length - 1;
        //flagL for left index is found and flagR for right index is found
        int flagL = 0;
        int flagR = 0;

        //Find left index
        while(left <= right){

            if(flagL == 0 && nums[left] == target){
                array[0] = left;
                flagL = 1;
                break;
            }else{
                left ++;
            }

        }

        //Find right index
        while(right >= left){

            if(flagR == 0 && nums[right] == target){
                array[1] = right;
                flagR = 1;
                break;
            }else{
                right --;
            }
        }

        //No find target
        if(flagL == 0 && flagR == 0){
            return array;
        }

        return array;
    }
}

Python代码 Accepted:

Two Points Search:

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        #array for the result
        array = [-1,-1]
        #flagL for left index is found
        flagL = 0
        #flagR for right index is found
        flagR = 0

        #two points left and righr
        left = 0
        right = len(nums) - 1

        #found left index
        while(left <= right):
            if(nums[left] == target):
                array[0] = left
                flagL = 1
                break
            else:
                left += 1
        #found right index
        while(right >= left):
            if(nums[right] == target):
                array[1] = right
                flagR = 1
                break
            else:
                right -= 1
        #no found target
        if(flagL == 0 and flagR == 0):
            return array

        return array
时间: 2024-10-29 02:38:23

LeetCode解题报告--Search for a Range的相关文章

leetCode解题报告5道题(九)

题目一:Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example,If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] 分析: 题意给我们一个数字n, 和一个数字k,让我们求出从 1~~n中取出k个数所能得到的组合数 所

leetCode解题报告5道题(十)

Disk Schedule Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 2368    Accepted Submission(s): 333 Problem Description 有很多从磁盘读取数据的需求,包括顺序读取.随机读取.为了提高效率,需要人为安排磁盘读取.然而,在现实中,这种做法很复杂.我们考虑一个相对简单的场景.磁

leetCode解题报告5道题(十一)

题目一:Subsets Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2]

LeetCode解题报告:LRU Cache

LRU Cache Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise retu

leetCode解题报告5道题(六)

题目一: Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the

leetCode解题报告5道题(八)

题目一: Populating Next Right Pointers in Each Node Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the

leetCode解题报告5道题(七)

先送上亚马逊传送门:<黑客与画家>:硅谷创业之父 Paul Graham 文集 再送上一个思维导图: 最好的办法就是自己创业或者加入创业公司 一个命题 命题 创业是一个压缩的过程,所有工作压缩成短短几年. 你不再是低强度的工作四十年,而是以极限强度工作四年 举例解释 一个优秀的黑客去除各种障碍,工作效率可以是在公司时的36倍. 假设他年薪8万美元,那么一个勤奋工作,摆脱杂事干扰的聪明黑客, 他的工作相当于年薪200万美元的价值 这里说的是极限情况,休闲时间为0,工作强度足以危害到健康. 守恒定

LeetCode解题报告:Reorder List

Reorder List Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do this in-place without altering the nodes' values. For example,Given {1,2,3,4}, reorder it to {1,4,2,3}. 思路: 1.利用快慢两个指针将链表一分为二: 2.针对第二个子链表求倒序

LeetCode解题报告:Linked List Cycle &amp;&amp; Linked List Cycle II

Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it without using extra space? Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follo