当前位置:网站首页>面试题 16.16. 部分排序-双指针法
面试题 16.16. 部分排序-双指针法
2022-07-01 18:45:00 【Mr Gao】
面试题 16.16. 部分排序
给定一个整数数组,编写一个函数,找出索引m和n,只要将索引区间[m,n]的元素排好序,整个数组就是有序的。注意:n-m尽量最小,也就是说,找出符合条件的最短序列。函数返回值为[m,n],若不存在这样的m和n(例如整个数组是有序的),请返回[-1,-1]。
示例:
输入: [1,2,4,7,10,11,7,12,6,7,16,18,19]
输出: [3,9]
解题代码如下:
/** * Note: The returned array must be malloced, assume caller calls free(). */
int* subSort(int* array, int arraySize, int* returnSize){
int low=0,high=arraySize-1;
int *re=(int *)malloc(sizeof(int)*2);
re[0]=-1;
re[1]=-1;
*returnSize=2;
if(arraySize<=1){
return re;
}
while(array[low]<=array[low+1]){
low++;
// printf("%d ",low);
if(low==arraySize-1){
return re;
}
}
while(array[high-1]<=array[high]){
high--;
if(high==0){
return re;
}
}
// printf("low high %d %d",low,high);
int i;
int min=999,max=-1000;
for(i=low;i<=high;i++){
if(array[i]<min){
min=array[i];
}
if(array[i]>max){
max=array[i];
}
}
// printf("min max %d %d",min,max);
while(array[low]>min){
if(low==0){
break;
}
low--;
if(low==0){
break;
}
}
while(array[high]<max){
if(high==arraySize){
break;
}
high++;
if(high==arraySize){
break;
}
}
if(low==0){
low--;
}
re[0]=low+1;
re[1]=high-1;
*returnSize=2;
return re;
}
边栏推荐
- Dom4J解析XML、Xpath检索XML
- 【pytorch记录】模型的分布式训练DataParallel、DistributedDataParallel
- Lean thinking: source, pillar, landing. I understand it after reading this article
- Cdga | if you are engaged in the communication industry, you should get a data management certificate
- CMU AI PhD 第一年总结
- How to redraw the header of CListCtrl in MFC
- Solidity - 合约结构 - 错误(error)- ^0.8.4版本新增
- kubernetes命令入门(namespaces,pods)
- M91快速霍尔测量仪—在更短的时间内进行更好的测量
- 见证时代!“人玑协同 未来已来”2022弘玑生态伙伴大会开启直播预约
猜你喜欢
随机推荐
uni-app商品分类
axure不显示元件库
[pytorch record] distributed training dataparallel and distributeddataparallel of the model
正则表达式=Regex=regular expression
新版国标GB28181视频平台EasyGBS如何配置WebRTC视频流格式播放?
如何正确使用Vertx操作Redis(3.9.4带源码分析)
[English grammar] Unit1 articles, nouns, pronouns and numerals
一次SQL优化,数据库查询速度提升 60 倍
Solidity - truncated and checked modes of arithmetic operations - new features of 0.8.0
Go语言高级
Transform + ASM data
transform + asm资料
The use of subplot function in MATLAB
有关 M91 快速霍尔测量仪的更多信息
记一次 .NET 差旅管理后台 CPU 爆高分析
PMP是被取消了吗??
Solution of intelligent supply chain management platform in aquatic industry: support the digitalization of enterprise supply chain and improve enterprise management efficiency
The intelligent epidemic prevention system provides safety guarantee for the resumption of work and production at the construction site
Witness the times! "The future of Renji collaboration has come" 2022 Hongji ecological partnership conference opens live broadcast reservation
ffmpeg 音频相关命令