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;
        }
        
    }
    
    }
  • 相关阅读:
    网页收藏
    background 和IMG的差异
    cefsharp开发实例1
    Node.js系列之node.js初探
    sublime3安装package controller遇到的问题
    java 指定日期加指定天数
    svn 命令
    mac下nodejs 更新到最新版本的最新方法
    mac系统安装redis
    sublime 安装插件
  • 原文地址:https://www.cnblogs.com/birdhack/p/4068913.html
Copyright © 2011-2022 走看看