(1)跟LeetCode中的:[LeetCode]33.Search in Rotated Sorted Array一样。
/*-----------------------------------------------------------
* 日期:2014-01-15
* 作者:SJF0115
* 题目: 33.Search in Rotated Sorted Array
* 来源:http://oj.leetcode.com/problems/search-in-rotated-sorted-array/
* 结果:AC
* 来源:LeetCode
* 总结:
---------------------------------------------------------------*/
#include <iostream>
#include <stdio.h>
using namespace std;
class Solution {
public:
//二分查找
int search(int A[], int n, int target) {
int start = 0,end = n-1;
int mid;
while(start <= end){
mid = (start + end) / 2;
if(A[mid] == target){
return mid;
}
//中间元素大于最左边元素则左部分为有序数组
else if(A[mid] >= A[start]){
//目标位于左部分
if(target >= A[start] && target <= A[mid]){
end = mid - 1;
}
//目标位于右部分
else{
start = mid + 1;
}
}
//中间元素小于最右边元素则右部分为有序数组
else{
//目标位于右部分
if(target <= A[end] && target >= A[mid]){
start = mid + 1;
}
//目标位于左部分
else{
end = mid - 1;
}
}
}
return -1;
}
};
int main() {
int result;
Solution solution;
int A[] = {3,1};
result = solution.search(A,2,1);
printf("Result:%d\n",result);
return 0;
}
关于更多二分查找问题:[经典面试题]二分查找问题汇总
(2)
#include<string>
#include<iostream>
using namespace std;
string Decode(string str){
string result;
int size = str.size();
if(size <= 0){
return result;
}//if
// 重复元素区间
int start = 0,end = 0;
// 重复次数
int count = 0;
for(int i = 0;i < size;++i){
// 数字
if(str[i] >= '0' && str[i] <= '9'){
count = count * 10 + str[i] - '0';
if(i == size || (str[i+1] < '0' || str[i+1] > '9')){
for(int j = 0;j < count;++j){
result += str.substr(start,end-start);
}//for
// 重新设定
start = i + 1;
end = i + 1;
count = 0;
}//if
}//if
// 字符
else{
++end;
}
}//for
return result;
}
int main(){
string str("love2big2gae4fff1");
cout<<Decode(str)<<endl;
return 0;
}