几道算法题
任意一串字符串 字符串里包含数字部分和一般的字符
例如 ad2ef35adx1wewe76
注意这个字符串 里面有4个数字 分别是 1 2 35 76 不考虑大数
将数字按照从小到大排序 组成一个新的字符串
要求制作一个函数来进行处理
假设是 fun(char*src,char*des)
{
}
src 输入字符串 ad2ef35adx1wewe76
des 输出字符串 1-2-35-76
view plaincopy to clipboardprint?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;
}
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;
}
一个整数数组,数组中元素按照大小先增后减,设计算法,给定元素求其在数组中的位置索引。
view plaincopy to clipboardprint?#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
补充:软件开发 , C语言 ,