二分查找
2016-02-26 10:57
169 查看
//二分查找,binary search //给定一个整数X和整数A0,A1,A2...AN-1,后者已排序(从小到大),求使得Ai=X的下标i, //如果X不在数据中,则返回-1. //时间复杂度O(logN),空间复杂度O(1) int BinarySearch(int nums[], int n, int x){ int first, last, mid; first = 0; last = n - 1; //我自己写的,但代码不够简洁 /*while (first != last){ mid = (first + last) / 2; if (nums[first] <= x && x < nums[mid]){ last = mid; } else{ first = mid + 1; } } if (nums[mid] == x){ return mid; } else{ return -1; }*/ //参照《数据结构与算法分析》,比较简洁明了 while (first <= last){ mid = (first + last) / 2; if (x < nums[mid]){ last = mid; } else if (x>nums[mid]){ first = mid + 1; } else{ return mid; } } return -1; } //Search in Rotated Sorted Array /*描述 Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. */ //从小到大排序, /*分析 二分查找,难度主要在于左右边界的确定。 */ //时间复杂度O(logN),空间复杂度O(1). int Search(int nums[], int n, int x){ int first, last, mid; first = 0; last = n - 1; while (first <= last){ mid = (first + last) / 2; if (x == nums[mid]){ return mid; } if (nums[first] <= nums[mid]){ //first部分没有rotate(分析错误) //first 到 Mid 递增, if (nums[first]<=x && x < nums[mid]){ last = mid; } else{ first = mid + 1; } } else{ //nums[first]>nums[mid] //first是从后面rotate来的,mid到last递增。 if (nums[mid] < x && x <= nums[last - 1]){ first = mid + 1; } else{ last = mid; } } } return -1; } /*Search in Rotated Sorted Array II*/ /* 描述 Follow up for ”Search in Rotated Sorted Array”: What if duplicates are allowed? Would this affect the run-time complexity? How and why? Write a function to determine if a given target is in the array. */ //时间复杂度O(n),空间复杂度O(1). bool Search2(int nums[], int n, int x){ int first, last, mid; first = 0; last = n - 1; while (first <= last){ mid = (first + last) / 2; if (x == nums[mid]){ return true; } else{ if (nums[first] < nums[mid]){ //first to mid is 递增 if (nums[first] <= x && x < nums[mid]){ last = mid; } else{ first = mid + 1; } } else if (nums[first]>nums[mid]){ //mid to last is 递增 if (nums[mid] < x && x <= nums[last]){ first = mid + 1; } else{ last = mid; } } else{ //nums[first]=nums[mid] //first 有重复,skip duplicate one first++; } } } return false; }
相关文章推荐
- Unity3D自定义以及Assets Store包导入
- 了解JavaScript 对象的属性操作
- object.observe数据绑定
- IO和NIO
- iOS开发之Bug汇总
- 同时跑两个TOMCAT
- <关于昨天的CCC>
- 函数名字重组
- JVM系列五:JVM监测&工具
- C++类型强制转换:static_cast const_cast reinterpret_cast dynamic_cast
- Java中的几种排序算法:冒泡排序,插入排序,二分法排序,简单排序,快速排序
- redis错误error记录
- MyBatis学习笔记(二) 关联关系
- spark&hbase integration
- glDepthFunc
- 移动端Web App自适应布局探索与总结
- 建造者模式
- WebServer类,常用于连接内网用
- c#日期计算
- Qcom平台控制backlight亮度