编程之美2.12--快速寻找满足条件的两个数
2016-07-26 18:29
483 查看
/*快速寻找满足条件的两个数--编程之美2.12*/ #include <iostream> using namespace std; /*快速排序算法*/ void swap(int a[], int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } int partition(int a[], int low, int high) { int key = a[low]; while(low < high) { while(low < high && a[high] >= key) {high--;} swap(a,low,high); while(low < high && a[low] <= key) {low++;} swap(a,low,high); } return low; } void quickSort(int a[], int low, int high) { if(low<high) { int key=partition(a,low,high); quickSort(a,low,key-1); quickSort(a,key+1,high); } } /*二分查找*/ bool binarySearch(int a[], int low, int high, int key) { while(low<=high) { int mid = low+(high-low)/2; // 直接使用(high + low) / 2 可能导致溢出,记住这个点定义是放在循环体内!!!别再犯低级错误 if(a[mid] == key ) { return true; } else if(a[mid] < key ) { low=mid+1; } else { high=mid-1; } } return false; } /*思路一: 先排序; 定义两个变量:left和right,分别指向数组的最左边和最右边的数; 若arr[left]+a[right]>sum right--;否则left++; 直到arr[left]+a[right]=sum为止 时间复杂度为:O(NlogN)*/ bool findSum1(int a[],int left,int right,int sum) { quickSort(a,left,right); //先排序 while(left<right) { if(a[left]+a[right]==sum) { return true; break; } else if(a[left]+a[right]<sum) { left++; } else{ right--; } } return false; } /*思路二: 先排序; 再在遍历数组的时候采用二分查找去查找sum-array[i]的值; 从而时间复杂度控制在O(NlogN) */ bool findSum2(int a[],int low,int high,int sum) { quickSort(a,low,high); for(int i=0; i<=high; i++) { if(binarySearch(a,i+1,high,sum-a[i]) == 1) { return true; break; } } return false; } /*思路三: 使用hash结构,即使用hash结构来代替二分查找,用空间换取时间 代码此处省略*/ int main() { int array[10] = {10,1,2,8,9,5,4,3,6,7}; cout<<findSum1(array,0,9,1)<<endl; cout<<findSum2(array,0,9,1)<<endl; return 0; }
相关文章推荐
- php <a href></a>链接地址中是php变量,链接文本也是php变量的代码处理方法
- SpringMVC 拦截器
- qt bck
- VS错误代码以及解决方案
- SpringMVC Redreict 请求的问题
- spring-boot+mybatis+pagehelper+Swagger2构建RESTful API
- java string字符串
- NOIP2003-加分二叉树-dp-区间型动态规划
- Python学习
- 关于编程比较好的一些书
- Java入门第三季-综合实战:简易扑克牌游戏
- java中数字基本运算、金额运算精度问题小结
- 如何提高代码能力
- springmvc+mybatis高效接口编程
- phpstorm+Xdebug断点调试PHP
- PHPStorm IntelliJ IDEA 代码缩进风格设置
- python几大排序算法
- MAC系统里JDK版本切换
- python学习笔记——异常
- springMVC 基础注意