1. 程式人生 > >day4-1107-查詢1-Search for a Range

day4-1107-查詢1-Search for a Range

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].

分析

已經排好了序,用二分查詢。

C++實現1

class Solution {
public:
	vector<int> searchRange(int A[], int n, int target) {
		const int l = distance(A, lower_bound(A, A + n, target));
		const int u = distance(A, prev(upper_bound(A, A + n, target)));
		if (A[l] != target) // not found
			return vector<int> { -1, -1 };
		else
			return vector<int> { l, u };
		}
};

C++實現2

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;


int lower_bound(vector<int>& arr, int key) {
    int half;
    int len = arr.size();
    int mid;
    int first = 0;
    while (len > 0) {
        half = len >> 1;
        mid = first + half;
        //in the right part
        if (arr[mid] < key) {
            first = mid + 1;
            //因為first=mid+1,所以這裡的len需要在減去half的基礎之上再減去1
            len = len - half - 1;
        } else {
            //in the left part
            len = half;
        }
    }
    return first;
}
int upper_bound(vector<int>& arr, int key) {
    int mid;
    int first = 0;
    int len = arr.size();
    int half;
    while (len > 0) {
        half = len >> 1;
        mid = half + first;
        if (arr[mid] > key) {//in the left part
            len = half;
        } else {//if arr[mid]<= key ,in the right part
            first = mid + 1;
            len = len - half - 1;
        }
    }
    return first;
}
	
class Solution {
public:
	vector<int> searchRange (vector<int>& arr,int target) {
		int lower = lower_bound(arr, target);
		int upper = upper_bound(arr, target);
		vector<int> res; 
		if (lower != -1)
			res.push_back(lower);
		res.push_back(upper-1);
		return res;
	}

};


int main(int argc, char** argv) {
	Solution sol;
	vector<int> arr1;
	arr1.push_back(5);
	arr1.push_back(7);
	arr1.push_back(7);
	arr1.push_back(8);
	arr1.push_back(8);
	arr1.push_back(10);
	
	int target = 8;
	vector<int> v =sol.searchRange(arr1,target);
	vector<int>::iterator it;
	for(it=v.begin(); it!=v.end();it++){	
		cout<<*it<<" "<<endl;	
	}
	system("pause"); 
	return 0;
}

備註

lower_bound演算法要求在已經按照非遞減順序排序的陣列中找到第一個大於等於給定值key的那個數,其基本實現原理是二分查詢。
 upper_bound函式要求在按照非遞減順序排好序的陣列中找到第一個大於給定值key的那個數,其基本實現原理是二分查詢。
兩種實現參考了stl中的實現方式,返回滿足條件的值在陣列中的下標。如果找不到滿足條件的值,將會返回陣列的大小,就像迭代器中的end一樣,對應有效下標的下一個值。

相關推薦

day4-1107-查詢1-Search for a Range

LeetCode-Search for a Range 題目 Given a sorted array of integers, find the starting and ending position of a given target value. Yo

【二分查詢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 m

【LeetCode & 劍指offer刷題】查詢與排序題8:Search for a Range

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...) Search for a Range Given an array of integers   nums   so

Search for a Range

new sorted param for art careful span get with O(logN) This question turns to find the first and last element of the target in a sorted

[leetcode-34-Search for a Range]

star earch tco leet ger ive sort size div Given an array of integers sorted in ascending order, find the starting and ending position of

[Leetcode] search for a range 尋找範圍

earch exit 查找 run grand order pan leetcode [] Given a sorted array of integers, find the starting and ending position of a given target v

Search for a Range問題

rgba 找到 lang 分法 ria http 並且 plan bin Search for a Range問題leetcodejava二分查找 1. 問題描述 Given an array of integers sorted in ascending or

34. Search for a Range

sea int mod style boolean color pan target -1 public class Solution { public int[] searchRange(int[] nums, int target) {

[LeetCode] Search for a Range

ted runt found vector class arch algorithm com pty Given an array of integers sorted in ascending order, find the starting and ending po

LeetCode-34. Search for a Range

改變 必須 條件篩選 col sea 二分法 tro 例子 spa 一、問題描述   給定一個升序排列的數組nums,和一個目標數target,找出nums中target的索引範圍。   例子:給定數組為{5, 7, 7, 8, 8, 10},target=8。返回{3,4

[LeetCode] 34. Search for a Range 搜索一個範圍(Find First and Last Position of Element in Sorted Array)

begin tro value 復雜 targe || art length controls 原題目:Search for a Range, 現在題目改為: 34. Find First and Last Position of Element in Sorted Arr

LeetCode Day28 Search for a Range

class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int left=0,right=nums.size()-1,mid;

[leetcode刷題筆記]34.Search for a Range

題目描述 Given an array of integers sorted in ascending order, find the starting and ending position

[Lintcode]61. Search for a Range/[Leetcode]34. Find First and Last Position of Element in Sorted Array

實現 put -o earch 時間復雜度 pytho desc NPU challenge [Lintcode]61. Search for a Range/[Leetcode]34. Find First and Last Position of Element in

第九周演算法分析與設計: Search for a Range

問題描述: Given an array of integers sorted in ascending order, find the starting and ending position

codeforces Round #440 A Search for Pretty Integers【hash/排序】

dash hash acad pro section cif close esp small A. Search for Pretty Integers 【題目鏈接】:http://codeforces.com/contest/872/problem/A tim

DAY4(PYTHON)列表的嵌套,range,for

lis ace 列表 sta col asf [1] 嵌套 python li=[‘a‘,‘b‘,‘開心‘,‘c‘] print(li[2].replace ( ‘ 心 ‘, ‘ kaixin ‘ ) ) 輸出:‘a‘,‘b‘,‘開kaixin‘,‘c‘ li= [‘abc

Get last week date range for a date in Java

this is Java Calendar based solution Date date = new Date(); Calendar c = Calendar.getInstance(); c.setTime(date); int i = c.get(Calend

A tool to search for cheat sheets, snippets etc. | Hacker News

Radium is a platform (client and optional server) for viewing reference articles, cheat sheets, snippets etc. written in Golang. Supports cheat.sh, tldr, l

Things You Learn After 1 Year of Day Trading for a Living

Things You Learn After 1 Year of Day Trading for a LivingI’ve made 20% ROI in 6 months and lost it all in a single month. Then I lost 30% in 10 trades the