//解法一:
/*逐个判断每个整数是不是丑数,不高效*/int GetUglyNumber_Solution1(intindex){
if (index <=0)
return0;
int number = 0;
int uglyFount = 0;
while (uglyFound < index){
++number;
if (IsUgly(number))
++uglyFound;
}
return number;
}
bool IsUgly(int number){
while (number%2==0)
number = number/2;
while (number%3==0)
number = number/3;
while (number%5==0)
number = number/5;
return (number==1)? true:false;
}
//解法二:创建数组保存已找到的丑数
int GetUglyNumber_Solution2(intindex){
if (index <=0)
return0;
int*pUglyNumbers = new int[index];
pUglyNumbers[0] = 1;
int nextUglyIndex = 1;
int*pMultiply2 = pUglyNumbers;
int*pMultiply3 = pUglyNumbers;
int*pMultiply5 = pUglyNumbers;
while (nextUglyIndex<index){
int min = Min(*pMultiply2*2,*pMultiply3*3,*pMultiply5*5);
pUglyNumbers[nextUglyIndex] = min;
while (*pMultiply2*2 <= pUglyNumbers[nextUglyIndex])
++pMultiply2;
while (*pMultiply3*3 <= pUglyNumbers[nextUglyIndex])
++pMultiply3;
while (*pMultiply5*5 <= pUglyNumbers[nextUglyIndex])
++pMultiply5;
++nextUglyIndex;
}
int ugly = pUglyNumbers[nextUglyIndex-1];
delete[] pUglyNumbers;
return ugly;
}
int Min(int number1,int number2,int number3){
int min = (number1<number2)?number1:number2;
min = (min<number3)?min:number3;
return min;
}
面试题:第一个只出现一次的字符
char FirstNotRepeatingChar(char *pString){
if (pString==NULL)
return'\0';
constint tableSize = 256;//ACSII 8位,Unicode 16位unsignedint hashTable[tableSize];
for (unsignedint i=0;i<tableSize;++i)
hashTable[i] = 0;
char *pHashKey = pString;
while (*(pHashKey) !='\0')
hashTable[*(pHashKey++)]++;
char *pHashKey = pString;
while (*(pHashKey) !='\0'){
if (hashTable[*pHashKey] == 1)
return *pHashKey;
++pHashKey;
}
return'\0';
}
/*举一反三:如果需要判断字符在字符串中出现的次数,可以考虑基于数组创建一个哈希表,以较小的空间消耗换取时间效率*/
面试题36:数组中的逆序对
/*基于归并排序*/
int InversePairs(int *data,int length){
if (data == NULL || length <= 0)
return0;
int *copy = new int[length];
for (int i=0;i<length;++i)
copy[i] = data[i];
int count = InversePairsCore(data,copy,0,length-1);
delete[] copy;
returncount;
}
int InversePairsCore(int *data,int *copy,int start,int end) {
if (start == end){
copy[start] = data[end];
return0;
}
int length = (end-start)/2;
int left = InversePairsCore(data,copy,start,start+length);
int right = InversePairsCore(data,copy,start+length+1,end);;
int i = start+length;
int j = end;
int indexCopy = end;
int count = 0;
while (i>=start && j>=start+length+1){
if (data[i] > copy[j]){
copy[indexCopy--] = data[i--];count += j-start-length;
}
else{
copy[indexCopy--] = data[j--];
}
}
for (;i>=start;--i)copy[indexCopy--] = data[i];for (;j>=start+length;--i)copy[indexCopy--] = data[j]; return left+right+count;
}