zoukankan      html  css  js  c++  java
  • 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].

    二分法查找,虽然AC了,但写的不太好。

    public class Solution {
        ArrayList<Integer> arrayList=new ArrayList<>();
        int[] res=new int[]{-1,-1};
        public int[] searchRange(int[] A, int target) {
            if (A.length==0) {
                return null;
            }
            int middle = (A.length-1)/2;
            int end=A.length-1;
            if (A[middle]>target) {
                search(A, 0, middle, target);
            }else if (A[middle]<target) {
                search(A, middle, end, target);
            } else {
                search(A, 0, middle, target);
                search(A, middle+1, end, target);
            }
            
            if (arrayList.isEmpty()) {
                return res;
            }else {
                res[0]=arrayList.get(0);
                res[1]=arrayList.get(arrayList.size()-1);
                return res;
            }
        }
        
        private void search(int[] A,int begin,int end,int target) {
            if(begin>end){
                return;
            }
            if (begin==end) {
                if (A[begin]==target) {
                    if (!arrayList.contains(begin)) {
                        arrayList.add(begin);
                    }
                                
                }
                return;
            }
        int middle = (begin+end)/2;
        if (A[middle]>target) {
            search(A, begin, middle, target);
            return;
        }
        if (A[middle]<target) {
            search(A, middle+1, end, target);
            return;
        }
        if (A[middle]==target) {
            search(A, begin, middle, target);
            search(A, middle+1, end, target);
            return;
        }
        
    }
    
    }
  • 相关阅读:
    springboot整合solr8.0
    Java学习笔记之JFileChooser的简单使用
    bootstrap-fileinput插件,上传成功后事件
    centos7中安装mysql8.0
    linux下安装mysql
    IDEA集成JRebel热部署和远程调试
    Flume学习之路 (一)Flume的基础介绍
    android studio的安装和卸载
    彻底卸载mysql
    电脑重装系统后各种环境和工具的安装配置
  • 原文地址:https://www.cnblogs.com/birdhack/p/4068913.html
Copyright © 2011-2022 走看看