des 输出字符串 1-2-35-76
void Convert(const char *str) { int res = 0; vector<int> vec; while (*str != '\0') { if (isdigit(*str)) { while (isdigit(*str)) { res = res * 10 + (*str - '0'); str++; } vec.push_back(res); } else { res = 0; str++; } } sort(vec.begin(), vec.end()); copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, "-")); cout<<endl; }
一个整数数组,数组中元素按照大小先增后减,设计算法,给定元素求其在数组中的位置索引。
#include "stdafx.h" #include <iostream> #include <vector> #include <iterator> #include <algorithm> using namespace std; //利用二分查找的思想,来获得最大元素的索引 int FindMax(int arr[], int n) { int low = 0; int high = n - 1; int mid = 0; while (low + 2 <= high) { mid = (low + high) / 2; if (arr[mid] > arr[mid-1] && (arr[mid] > arr[mid+1])) //the max element return mid; else if (arr[mid] > arr[mid-1] && (arr[mid+1] > arr[mid])) //递增部分 low = mid; else high = mid; } } //递增部分的二分查找 int BinSearchLeft(int arr[], int begin, int end, int target) { int low = begin; int high = end - 1; int mid = 0; while (low <= high) { mid = (low + high) / 2; if (arr[mid] == target) return mid; else if (arr[mid] < target) low = mid + 1; else high = mid - 1; } return -1; } //递减部分的二分查找 int BinSearchRight(int arr[], int begin, int end, int target) { int low = begin; int high = end - 1; int mid = 0; while (low <= high) { mid = (low + high) / 2; if (arr[mid] == target) return mid; else if (arr[mid] > target) low = mid + 1; else high = mid - 1; } return -1; } //算法思想:先找到最大元素的索引,然后对左右两个部分进行二分查找 int FindTargetIndex(int arr[], int n, int target) { int maxIndex = FindMax(arr, n); if (arr[maxIndex] == target) return maxIndex; int res = 0; if ((res = BinSearchLeft(arr, 0, maxIndex, target)) != -1) return res; if ((res = BinSearchRight(arr, maxIndex + 1, n, target)) != -1) return res; return -1; } int main() { int arr[] = {2, 3, 4, 5, 10, 7, 6, 1}; int size = sizeof(arr) / sizeof(int); int maxIndex = FindMax(arr, size); if (-1 != maxIndex) cout<<"the max element's index is "<<maxIndex<<", the max elemet is "<<arr[maxIndex]<<endl; int res = FindTargetIndex(arr, size, 3); if (-1 != res) cout<<"the target's position is "<<res<<endl; else cout<<"can not find this target!"<<endl; return 0; }
函数将字符串中的字符'*'移到串的前部分,前面的非'*'字符后移,但不能改变非'*'字符的先后顺序,函数返回串中字符'*'的数量。如原始串为:ab**cd**e*12,处理后为*****abcde12,函数并返回值为5。(要求使用尽量少的时间和辅助空间)
#include "stdafx.h" #include <iostream> using namespace std; /************************************************************************/ /* 算法思想:两个指针i和j,从后往前扫。i指针碰到*表示该位置要放一个数,j指针从i的前一个字符开始扫, 如果不是星,则把该字符放到i指针所指向的地方,i指针向前走一位,j指针的字符置成*,如此扫到头即可 * /************************************************************************/ int ChangeStr(char *str) { int len = strlen(str); int res = 0; char *pRead = str + len - 1; char *pWrite = str + len - 1; while (pRead >= str) { if (*pRead != '*') { *pWrite = *pRead; pWrite--; pRead--; } else { pRead--; res++; } } memset(str, '*', res); return res; } int main() { char str[] = "ab**cd**e*12"; int res = ChangeStr(str); cout<<res<<endl; cout<<str<<endl; }