剑指offer例题分享--6

时间:2022-11-12 05:50:15

  前言:继续整理例题,快速做完这部分,然后继续用C++去刷数据结构和算法的题。

  面试题28:

  剑指offer例题分享--6

    代码如下:

    

#include<iostream>
#include<stdio.h>
using namespace std; void Permutation(char *pStr,char *pBegin)
{
if(*pBegin == '\0')
{
printf("str:%s\n",pStr);
}
else
{
for(char *pCh=pBegin;*pCh!='\0';++pCh)
{
char temp = *pCh;
*pCh = *pBegin;
*pBegin = temp; Permutation(pStr,pBegin+); temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
}
}
} void Permutation(char *pStr)
{
if(pStr == NULL)
return; Permutation(pStr,pStr);
} int main()
{
char buf[]="asd";
Permutation(buf);
return ;
}

  面试题29:

  剑指offer例题分享--6

  代码如下:

  

/*************************************************************************
> File Name: 29.cpp
> Author: ma6174
> Mail: ma6174@163.com
> Created Time: Tue 14 Aug 2018 09:45:42 AM CST
************************************************************************/ #include<iostream>
using namespace std; bool g_bInputInvalid =false; bool CheckInvalidArray(int *numbers,int len)
{
if(numbers==NULL && len<=)
g_bInputInvalid = true; return g_bInputInvalid;
} bool CheckMoreThanHalf(int *numbers,int len,int num)
{
int times = ;
for(int i=;i<len;++i)
{
if(numbers[i] == num)
times++;
} bool isMoreThanHalf = true;
if(times* < len)
{
g_bInputInvalid = true;
isMoreThanHalf = false;
} return isMoreThanHalf;
} int MoreThanHalfNum(int *numbers,int len)
{
if(CheckInvalidArray(numbers,len))
return ; int result = numbers[];
int times = ;
for(int i=;i<len;++i)
{
if(times == )
{
result = numbers[i];
times = ;
}
else if(numbers[i] == result)
times++;
else
times--;
} if(!CheckMoreThanHalf(numbers,len,result))
result = ;
return result;
} int main()
{
int data[]={,,,,,,};
cout << "num: " << MoreThanHalfNum(data,) << endl;; return ;
}

  面试题30:

  剑指offer例题分享--6 

    分析:一定要对C++的STL熟悉,才能看明白如下代码:

#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<iterator>
using namespace std; //greater<int>()是一个预定义函数对象,将multiset容器从大到小排序
typedef multiset<int,greater<int> > intSet;
typedef multiset<int,greater<int> >::iterator setIterator; void GetLeastNumbers(const vector<int> &data,intSet &leastNumbers,int k)
{
//清空容器
leastNumbers.clear(); if(k< || data.size()<k)
return; //创建迭代器
vector<int>::const_iterator iter = data.begin();
for(;iter!=data.end();++iter)
{
//小于k插入容器
if((leastNumbers.size())<k)
leastNumbers.insert(*iter);
else{
setIterator iteraCreatest = leastNumbers.begin();
//如果插入的数比容器中的最大值小,则删除
if(*iter < *(leastNumbers.begin()))
{
leastNumbers.erase(iteraCreatest);
leastNumbers.insert(*iter);
}
}
}
} int main()
{
vector<int> data();
data[] = ;
data[] = ;
data[] = ;
data[] = ;
intSet set;
GetLeastNumbers(data,set,);
//iterate over all elements and print them
intSet::iterator pos;
for (pos = set.begin(); pos != set.end(); ++pos) {
cout << *pos << ' ';
}
cout << endl; return ;
}