java 范圍搜尋要怎么弄_搜索范圍

java 范圍搜尋要怎么弄

Problem statement:

問題陳述:

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

給定一個以升序排列的整數nums數組,請找到給定目標值的開始和結束位置。

Your algorithm's runtime complexity must be in order to less than O(n).

您的算法的運行時復雜度必須小于O(n)

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

如果在數組中找不到目標,則返回[-1,-1]

Constraints:

限制條件:

1 <= t <= 100
1 <= n <= 1000000

Example:

例:

Test case 1:
Input: 
arr = [5,6,7,8,8,10]
target = 8
Output: 
range is : [3, 4]
Test case 2:
Input: 
arr = [5,7,7,8,8,10]
target = 6
Output:
range is: [-1,-1]

Explanation:

說明:

Though the above solutions are self-explanatory,
still for the first test case,
For the first test case,
Target is first present at index 3 and 
last one at 4. (0-based indexing)
For the second test case,
Target is not at all present and 
hence range is [-1,-1]

Solution approach

解決方法

It's quite similar to binary search. The modification is to not to stop when you get the target find. Search for the upper and lower elements to check if they are the same or not.

它與二進制搜索非常相似。 修改是在找到目標時不要停止。 搜索上部和下部元素以檢查它們是否相同。

Here goes the full algorithm,

這里是完整的算法,

  1. Initialize the result range to be [-1,-1]

    初始化結果范圍為[-1,-1]

  2. If array size is 0

    如果數組大小為0

    return

    返回

    result;

    結果 ;

  3. Initialize left = 0, right = n-1;

    初始化left = 0,right = n-1;

  4. while(left<=right)
    mid=(left+right)/2;
    if(nums[mid]==target) //once found search for range
    set i=mid;
    set j=mid;
    while(i>=left && nums[i]==target)
    Decrease i;
    while(j<=right && nums[j]==target)
    Increase j;
    Result is [i+1,j-1]            		
    else if(nums[mid]<target)
    left=mid+1;
    else
    right=mid-1;
    end if
    End while
    
    
  5. Result stores the starting and ending point of range. If target is not found then the range will be the initial one, [-1,-1]

    結果存儲范圍的起點和終點。 如果找不到目標,則范圍將是初始范圍[-1,-1]

Let's solve with the first test case,
left = 0
right = 5
mid = 2
a[mid]<target, left = mid+1 = 3
a[mid] == target
so traverse left and right from this
range found to be [3,4]
For the second test case,
It simple comes out of the loop

C++ Implementation:

C ++實現:

#include <bits/stdc++.h>
using namespace std;
vector<int> searchRange(vector<int>& nums, int target)
{
int n = nums.size();
vector<int> p(2, -1);
if (n == 0)
return p;
int left = 0, right = n - 1;
int mid;
while (left <= right) {
mid = (left + right) / 2;
if (nums[mid] == target) { //once found search for range
int i = mid;
int j = mid;
while (i >= left && nums[i] == target)
i--;
while (j <= right && nums[j] == target)
j++;
p[0] = i + 1;
p[1] = j - 1;
return p;
}
else if (nums[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return p;
}
int main()
{
int t;
cout << "Enter number of testcases\n";
cin >> t;
while (t--) {
int n;
cout << "Enter length of array\n";
cin >> n;
cout << "Enter the sorted vector\n";
vector<int> arr(n);
for (int i = 0; i < n; i++)
cin >> arr[i];
int k;
cout << "Enter target no\n";
cin >> k;
vector<int> result = searchRange(arr, n);
cout << "range is: [" << result[0] << "," << result[1] << "]\n";
}
return 0;
}

Output:

輸出:

Enter number of testcases
2
Enter length of array
6
Enter the sorted vector
5 6 7 8 8 10
Enter target no
8
range is: [3,4]
Enter length of array
6
Enter the sorted vector
5 7 7 8 8 10
Enter target no
6
range is: [-1,-1]

翻譯自: https://www.includehelp.com/icp/search-for-a-range.aspx

java 范圍搜尋要怎么弄

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377078.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377078.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377078.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

boa + ajax + cgi ajax請求cgi

最近公司要做一個通訊管理機,然后需要和另外一個同事一起做,我們需要用到boaAjaxCGI,以前沒試過與CGI交互,一開始發現問題挺大的,用ajax請求cgi,總是不返回數據,又或者請求回來的是cgi的源碼,后來發現,通過本地IIS或者直接打開html頁面請求的,返回來的都是cgi的源碼或者返回失敗…

《DBNotes:single_table訪問方法、MRR多范圍讀取優化、索引合并》

目錄single_table訪問方法constrefref_or_nullrangeindexallMRR多范圍讀取優化索引合并intersectionunionsort-unionsingle_table訪問方法 const 在主鍵列或者unique二級索引與一個常數進行等值比較時才有效。 如果主鍵或者unique二級索引的索引列由多個列構成&#xff0c;則…

怎樣通過命令管理Windows7桌面防火墻

&#xff08;1&#xff09;啟用桌面防火墻netsh advfirewall set allprofiles state on&#xff08;2&#xff09;設置默認輸入和輸出策略netsh advfirewall set allprofiles firewallpolicy allowinbound,allowoutbound以上是設置為允許&#xff0c;如果設置為拒絕使用blockin…

ruby推送示例_Ruby for循環示例

ruby推送示例for循環 (The for loop) In programming, for loop is a kind of iteration statement which allows the block to be iterated repeatedly as long as the specified condition is not met or a specific number of times that the programmer knows beforehand. …

《DBNotes: Buffer Pool對于緩沖頁的鏈表式管理》

目錄Buffer Pool回顧Buffer Pool內部組成freelistflushlistLRU鏈表管理以及改進Buffer Pool回顧 我們知道針對數據庫的增刪改刪操作都是在Buffer Pool中完成的&#xff0c;一條sql的執行步驟可以認為是這樣的&#xff1a; 1、innodb存儲引擎首先在緩沖池中查詢有沒有對應的數據…

一個延時調用問題

如果用下面第1行的寫法&#xff0c;調用 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector(removeFromSuperview) object:nil]; 可以生效 如果用下面第3行的寫法&#xff0c;調用 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:…

onclicklistener 方法使用匯總

相信很多像我一樣的新手學習ANDROID開發會遇到這個問題&#xff0c;通過這幾天的歸類和總結&#xff0c;將我的理解寫在下面&#xff0c;歡迎大家一起前來討論&#xff1a; 以按鈕BUTTON的監聽事件為例&#xff0c;以下的監聽實現都是等價的&#xff1a; 1.使用接口繼承按鈕監聽…

《源碼分析轉載收藏向—數據庫內核月報》

月報原地址&#xff1a; 數據庫內核月報 現在記錄一下&#xff0c;我可能需要參考的幾篇文章吧&#xff0c;不然以后還得找&#xff1a; MySQL 代碼閱讀 MYSQL開源軟件源碼閱讀小技巧 MySQL 源碼分析 聚合函數&#xff08;Aggregate Function&#xff09;的實現過程 MySQL …

vim中的jk為什么是上下_JK的完整形式是什么?

vim中的jk為什么是上下JK&#xff1a;開玩笑 (JK: Just Kidding) JK is an abbreviation of "Just Kidding". JK是“ Just Kidding”的縮寫 。 It is an expression, which is commonly used in messaging or chatting on social media networking sites like Faceb…

百度歸來的學長做報告

今天下午下課到現在才總算閑下來&#xff0c;本來計劃這個時間應該是讀英語&#xff0c;做英語模擬題的時間&#xff0c;但是&#xff0c;我不得不寫點什么來記錄下剛才的事——在百度實習并且簽下工作的學長做報告。 原本認為每個人的成功&#xff08;請允許我目前的眼光簽個好…

轉:Google論文之三----MapReduce

文章來自于&#xff1a;http://www.cnblogs.com/geekma/p/3139823.html MapReduce&#xff1a;大型集群上的簡單數據處理 摘要 MapReduce是一個設計模型&#xff0c;也是一個處理和產生海量數據的一個相關實現。用戶指定一個用于處理一個鍵值&#xff08;key-value&#xff09;…

合約 cd 模式_CD的完整形式是什么?

合約 cd 模式CD&#xff1a;光盤 (CD: Compact Disc) CD is an abbreviation of "Compact Disc". CD是“ Compact Disc”的縮寫 。 It is a digital optical disc originally developed to store the audio of recordings in the format of a data file used as a p…

《DBNotes:Join算法的前世今生》

目錄NestLoopJoin算法Simple Nested-Loop JoinIndex Nested-Loop JoinBlock Nested-Loop JoinBatched Key AccessHash Join算法In-Memory Join(CHJ)On-Disk Hash Join參考鏈接在8.0.18之前&#xff0c;MySQL只支持NestLoopJoin算法&#xff0c;最簡單的就是Simple NestLoop Joi…

如何解決迅雷插件導致IE10崩潰的問題

Windows 8里面帶的IE10酷不酷&#xff1f;沉浸式界面果然不同凡響&#xff0c;IE10讓人幾乎認不出來了&#xff01;這是微軟的瀏覽器么&#xff1f;上面這張圖是Windows8下Metro UI的新界面IE10&#xff0c;不過當我們切換回傳統桌面的時候&#xff0c;也有IE10的經典版的。好吧…

UNITY3D與iOS交互解決方案

原地址&#xff1a;http://bbs.18183.com/thread-456979-1-1.html 本帖最后由 啊,將進酒 于 2014-2-27 11:17 編輯 “授人以魚&#xff0c;不如授人以漁”&#xff0c;以UNITY3D調用iOS版的91SDK為例&#xff0c;利用C# / C / OBJ-C交互原理,本文將詳細介紹UNITY3D與iOS之間交互…

c:if equal_C ++中的std :: equal()

c:if equalequal()作為STL函數 (equal() as a STL function) Syntax: 句法&#xff1a; bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2);Where, 哪里&#xff0c; InputIterator1 first iterator to start of the first sequence range I…

《DBNotes:Buffer Pool刷臟頁細節以及改進》

本筆記知識沿用之前DBNotes: Buffer Pool對于緩沖頁的鏈表式管理的部分知識 目錄獲取一個空閑頁的源碼邏輯Page_Cleaner_ThreadLRU_Manager_ThreadHazard Pointer作為驅逐算法改進參考獲取一個空閑頁的源碼邏輯 任何一個讀寫請求都需要從Buffer pool來獲取所需頁面。如果需要的…

WordPress刪除數據中標題重復文章的方法

一種是刪除重復的方法是&#xff1a;使用插件,大家可以去官網上下載 二種刪除重復的方法是&#xff1a;登錄數據庫&#xff0c;使用sql語句刪除&#xff0c;具體的語句為如下代碼&#xff1a; CREATE TABLE my_tmp AS SELECT MIN(ID) AS col1 FROM wp_posts GROUP BY post_titl…

hibernate配置

hibernate.cfg.xml <?xml version"1.0" encoding"UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd&quo…

html中表單元素_HTML中的表單元素

html中表單元素1)<input>元素 (1) The <input> Element) The <input> element is used to get input from the user in an HTML form. <input>元素用于以HTML形式從用戶獲取輸入。 <input> tag is used to get input using input element, the …