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.mzph.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 …