数字数组
目录:
3、【剑指Offer学习】【面试题03:找出数组中重复的数字】
11、【剑指Offer学习】【面试题11:旋转数组的最小数字】
21、【剑指Offer学习】【面试题21:调整数组顺序使奇数位于偶数前面】
39、【剑指Offer学习】【面试题39:数组中出现次数超过一半的数字】
42、【剑指Offer学习】【面试题42:连续子数组的最大和】
43、【剑指Offer学习】【面试题43:从1到n整数中1出现的次数】
44、【剑指Offer学习】【面试题44:数字序列中某一位的数字】
45、【剑指Offer学习】【面试题45:把数组排成最小的数】
53、【剑指Offer学习】【面试题53:数字在排序数组中出现的次数】
56、【剑指Offer学习】【面试题56:数组中只出现一次的两个数字】
57、【剑指Offer学习】【面试题57:和为s的两个数字】
62、【剑指Offer学习】【面试题62:圆圈中最后剩下的数字】
3. 面试题03:找出数组中重复的数字
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题3(一):找出数组中重复的数字
// 题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,
// 也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。例如,如果输入长度为7的数组{2, 3, 1, 0, 2, 5, 3},
// 那么对应的输出是重复的数字2或者3。
#include <cstdio>
// 参数:
// numbers: 一个整数数组
// length: 数组的长度
// duplication: (输出) 数组中的一个重复的数字
// 返回值:
// true - 输入有效,并且数组中存在重复的数字
// false - 输入无效,或者数组中没有重复的数字
bool duplicate(int numbers[], int length, int* duplication)
{
if(numbers == nullptr || length <= 0)
return false;
for(int i = 0; i < length; ++i)
{
if(numbers[i] < 0 || numbers[i] > length - 1)
return false;
}
for(int i = 0; i < length; ++i)
{
while(numbers[i] != i)
{
if(numbers[i] == numbers[numbers[i]])
{
*duplication = numbers[i];
return true;
}
// 交换numbers[i]和numbers[numbers[i]]
int temp = numbers[i];
numbers[i] = numbers[temp];
numbers[temp] = temp;
}
}
return false;
}
// ====================测试代码====================
bool contains(int array[], int length, int number)
{
for(int i = 0; i < length; ++i)
{
if(array[i] == number)
return true;
}
return false;
}
void test(char* testName, int numbers[], int lengthNumbers, int expected[], int expectedExpected, bool validArgument)
{
printf("%s begins: ", testName);
int duplication;
bool validInput = duplicate(numbers, lengthNumbers, &duplication);
if(validArgument == validInput)
{
if(validArgument)
{
if(contains(expected, expectedExpected, duplication))
printf("Passed.\n");
else
printf("FAILED.\n");
}
else
printf("Passed.\n");
}
else
printf("FAILED.\n");
}
// 重复的数字是数组中最小的数字
void test1()
{
int numbers[] = { 2, 1, 3, 1, 4 };
int duplications[] = { 1 };
test("Test1", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int), true);
}
// 重复的数字是数组中最大的数字
void test2()
{
int numbers[] = { 2, 4, 3, 1, 4 };
int duplications[] = { 4 };
test("Test2", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int), true);
}
// 数组中存在多个重复的数字
void test3()
{
int numbers[] = { 2, 4, 2, 1, 4 };
int duplications[] = { 2, 4 };
test("Test3", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int), true);
}
// 没有重复的数字
void test4()
{
int numbers[] = { 2, 1, 3, 0, 4 };
int duplications[] = { -1 }; // not in use in the test function
test("Test4", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int), false);
}
// 没有重复的数字
void test5()
{
int numbers[] = { 2, 1, 3, 5, 4 };
int duplications[] = { -1 }; // not in use in the test function
test("Test5", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int), false);
}
// 无效的输入
void test6()
{
int* numbers = nullptr;
int duplications[] = { -1 }; // not in use in the test function
test("Test6", numbers, 0, duplications, sizeof(duplications) / sizeof(int), false);
}
void main()
{
test1();
test2();
test3();
test4();
test5();
test6();
while(1);
}
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题3(二):不修改数组找出重复的数字
// 题目:在一个长度为n+1的数组里的所有数字都在1到n的范围内,所以数组中至
// 少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的
// 数组。例如,如果输入长度为8的数组{2, 3, 5, 4, 3, 2, 6, 7},那么对应的
// 输出是重复的数字2或者3。
#include <iostream>
int countRange(const int* numbers, int length, int start, int end);
// 参数:
// numbers: 一个整数数组
// length: 数组的长度
// 返回值:
// 正数 - 输入有效,并且数组中存在重复的数字,返回值为重复的数字
// 负数 - 输入无效,或者数组中没有重复的数字
int getDuplication(const int* numbers, int length)
{
if(numbers == nullptr || length <= 0)
return -1;
int start = 1;
int end = length - 1;
while(end >= start)
{
int middle = ((end - start) >> 1) + start;
int count = countRange(numbers, length, start, middle);
if(end == start)
{
if(count > 1)
return start;
else
break;
}
if(count > (middle - start + 1))
end = middle;
else
start = middle + 1;
}
return -1;
}
int countRange(const int* numbers, int length, int start, int end)
{
if(numbers == nullptr)
return 0;
int count = 0;
for(int i = 0; i < length; i++)
if(numbers[i] >= start && numbers[i] <= end)
++count;
return count;
}
// ====================测试代码====================
void test(const char* testName, int* numbers, int length, int* duplications, int dupLength)
{
int result = getDuplication(numbers, length);
for(int i = 0; i < dupLength; ++i)
{
if(result == duplications[i])
{
std::cout << testName << " passed." << std::endl;
return;
}
}
std::cout << testName << " FAILED." << std::endl;
}
// 多个重复的数字
void test1()
{
int numbers[] = { 2, 3, 5, 4, 3, 2, 6, 7 };
int duplications[] = { 2, 3 };
test("test1", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}
// 一个重复的数字
void test2()
{
int numbers[] = { 3, 2, 1, 4, 4, 5, 6, 7 };
int duplications[] = { 4 };
test("test2", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}
// 重复的数字是数组中最小的数字
void test3()
{
int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 1, 8 };
int duplications[] = { 1 };
test("test3", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}
// 重复的数字是数组中最大的数字
void test4()
{
int numbers[] = { 1, 7, 3, 4, 5, 6, 8, 2, 8 };
int duplications[] = { 8 };
test("test4", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}
// 数组中只有两个数字
void test5()
{
int numbers[] = { 1, 1 };
int duplications[] = { 1 };
test("test5", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}
// 重复的数字位于数组当中
void test6()
{
int numbers[] = { 3, 2, 1, 3, 4, 5, 6, 7 };
int duplications[] = { 3 };
test("test6", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}
// 多个重复的数字
void test7()
{
int numbers[] = { 1, 2, 2, 6, 4, 5, 6 };
int duplications[] = { 2, 6 };
test("test7", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}
// 一个数字重复三次
void test8()
{
int numbers[] = { 1, 2, 2, 6, 4, 5, 2 };
int duplications[] = { 2 };
test("test8", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}
// 没有重复的数字
void test9()
{
int numbers[] = { 1, 2, 6, 4, 5, 3 };
int duplications[] = { -1 };
test("test9", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}
// 无效的输入
void test10()
{
int* numbers = nullptr;
int duplications[] = { -1 };
test("test10", numbers, 0, duplications, sizeof(duplications) / sizeof(int));
}
void main()
{
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
test10();
}
4. 【剑指Offer学习】【面试题04:二维数组中的查找<】
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题4:二维数组中的查找
// 题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按
// 照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个
// 整数,判断数组中是否含有该整数。
#include <cstdio>
bool Find(int* matrix, int rows, int columns, int number)
{
bool found = false;
if(matrix != nullptr && rows > 0 && columns > 0)
{
int row = 0;
int column = columns - 1;
while(row < rows && column >=0)
{
if(matrix[row * columns + column] == number)
{
found = true;
break;
}
else if(matrix[row * columns + column] > number)
-- column;
else
++ row;
}
}
return found;
}
// ====================测试代码====================
void Test(char* testName, int* matrix, int rows, int columns, int number, bool expected)
{
if(testName != nullptr)
printf("%s begins: ", testName);
bool result = Find(matrix, rows, columns, number);
if(result == expected)
printf("Passed.\n");
else
printf("Failed.\n");
}
// 1 2 8 9
// 2 4 9 12
// 4 7 10 13
// 6 8 11 15
// 要查找的数在数组中
void Test1()
{
int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
Test("Test1", (int*)matrix, 4, 4, 7, true);
}
// 1 2 8 9
// 2 4 9 12
// 4 7 10 13
// 6 8 11 15
// 要查找的数不在数组中
void Test2()
{
int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
Test("Test2", (int*)matrix, 4, 4, 5, false);
}
// 1 2 8 9
// 2 4 9 12
// 4 7 10 13
// 6 8 11 15
// 要查找的数是数组中最小的数字
void Test3()
{
int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
Test("Test3", (int*)matrix, 4, 4, 1, true);
}
// 1 2 8 9
// 2 4 9 12
// 4 7 10 13
// 6 8 11 15
// 要查找的数是数组中最大的数字
void Test4()
{
int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
Test("Test4", (int*)matrix, 4, 4, 15, true);
}
// 1 2 8 9
// 2 4 9 12
// 4 7 10 13
// 6 8 11 15
// 要查找的数比数组中最小的数字还小
void Test5()
{
int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
Test("Test5", (int*)matrix, 4, 4, 0, false);
}
// 1 2 8 9
// 2 4 9 12
// 4 7 10 13
// 6 8 11 15
// 要查找的数比数组中最大的数字还大
void Test6()
{
int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
Test("Test6", (int*)matrix, 4, 4, 16, false);
}
// 鲁棒性测试,输入空指针
void Test7()
{
Test("Test7", nullptr, 0, 0, 16, false);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
return 0;
}
11. 面试题11:旋转数组的最小数字
/******************************************************************* Copyright(c) 2016, Harry He All rights reserved. Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题11:旋转数组的最小数字
// 题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
// 输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如数组
// {3, 4, 5, 1, 2}为{1, 2, 3, 4, 5}的一个旋转,该数组的最小值为1。
#include <cstdio>
#include <exception>
int MinInOrder(int* numbers, int index1, int index2);
int Min(int* numbers, int length)
{
if(numbers == nullptr || length <= 0)
throw new std::exception("Invalid parameters");
int index1 = 0;
int index2 = length - 1;
int indexMid = index1;
while(numbers[index1] >= numbers[index2])
{
// 如果index1和index2指向相邻的两个数,
// 则index1指向第一个递增子数组的最后一个数字,
// index2指向第二个子数组的第一个数字,也就是数组中的最小数字
if(index2 - index1 == 1)
{
indexMid = index2;
break;
}
// 如果下标为index1、index2和indexMid指向的三个数字相等,
// 则只能顺序查找
indexMid = (index1 + index2) / 2;
if(numbers[index1] == numbers[index2] && numbers[indexMid] == numbers[index1])
return MinInOrder(numbers, index1, index2);
// 缩小查找范围
if(numbers[indexMid] >= numbers[index1])
index1 = indexMid;
else if(numbers[indexMid] <= numbers[index2])
index2 = indexMid;
}
return numbers[indexMid];
}
int MinInOrder(int* numbers, int index1, int index2)
{
int result = numbers[index1];
for(int i = index1 + 1; i <= index2; ++i)
{
if(result > numbers[i])
result = numbers[i];
}
return result;
}
// ====================测试代码====================
void Test(int* numbers, int length, int expected)
{
int result = 0;
try
{
result = Min(numbers, length);
for(int i = 0; i < length; ++i)
printf("%d ", numbers[i]);
if(result == expected)
printf("\tpassed\n");
else
printf("\tfailed\n");
}
catch (...)
{
if(numbers == nullptr)
printf("Test passed.\n");
else
printf("Test failed.\n");
}
}
int main(int argc, char* argv[])
{
// 典型输入,单调升序的数组的一个旋转
int array1[] = { 3, 4, 5, 1, 2 };
Test(array1, sizeof(array1) / sizeof(int), 1);
// 有重复数字,并且重复的数字刚好的最小的数字
int array2[] = { 3, 4, 5, 1, 1, 2 };
Test(array2, sizeof(array2) / sizeof(int), 1);
// 有重复数字,但重复的数字不是第一个数字和最后一个数字
int array3[] = { 3, 4, 5, 1, 2, 2 };
Test(array3, sizeof(array3) / sizeof(int), 1);
// 有重复的数字,并且重复的数字刚好是第一个数字和最后一个数字
int array4[] = { 1, 0, 1, 1, 1 };
Test(array4, sizeof(array4) / sizeof(int), 0);
// 单调升序数组,旋转0个元素,也就是单调升序数组本身
int array5[] = { 1, 2, 3, 4, 5 };
Test(array5, sizeof(array5) / sizeof(int), 1);
// 数组中只有一个数字
int array6[] = { 2 };
Test(array6, sizeof(array6) / sizeof(int), 2);
// 输入nullptr
Test(nullptr, 0, 0);
return 0;
}
16. 面试题16:数值的整数次方
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题16:数值的整数次方
// 题目:实现函数double Power(double base, int exponent),求base的exponent
// 次方。不得使用库函数,同时不需要考虑大数问题。
#include <iostream>
#include <cmath>
bool g_InvalidInput = false;
bool equal(double num1, double num2);
double PowerWithUnsignedExponent(double base, unsigned int exponent);
double Power(double base, int exponent)
{
g_InvalidInput = false;
if (equal(base, 0.0) && exponent < 0)
{
g_InvalidInput = true;
return 0.0;
}
unsigned int absExponent = (unsigned int) (exponent);
if (exponent < 0)
absExponent = (unsigned int) (-exponent);
double result = PowerWithUnsignedExponent(base, absExponent);
if (exponent < 0)
result = 1.0 / result;
return result;
}
/*
double PowerWithUnsignedExponent(double base, unsigned int exponent)
{
double result = 1.0;
for (int i = 1; i <= exponent; ++i)
result *= base;
return result;
}
*/
double PowerWithUnsignedExponent(double base, unsigned int exponent)
{
if (exponent == 0)
return 1;
if (exponent == 1)
return base;
double result = PowerWithUnsignedExponent(base, exponent >> 1);
result *= result;
if ((exponent & 0x1) == 1)
result *= base;
return result;
}
bool equal(double num1, double num2)
{
if ((num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001))
return true;
else
return false;
}
// ====================测试代码====================
void Test(const char* testName, double base, int exponent, double expectedResult, bool expectedFlag)
{
double result = Power(base, exponent);
if (equal(result, expectedResult) && g_InvalidInput == expectedFlag)
std::cout << testName << " passed" << std::endl;
else
std::cout << testName << " FAILED" << std::endl;
}
int main(int argc, char* argv[])
{
// 底数、指数都为正数
Test("Test1", 2, 3, 8, false);
// 底数为负数、指数为正数
Test("Test2", -2, 3, -8, false);
// 指数为负数
Test("Test3", 2, -3, 0.125, false);
// 指数为0
Test("Test4", 2, 0, 1, false);
// 底数、指数都为0
Test("Test5", 0, 0, 1, false);
// 底数为0、指数为正数
Test("Test6", 0, 4, 0, false);
// 底数为0、指数为负数
Test("Test7", 0, -4, 0, true);
return 0;
}
21. 面试题21:调整数组顺序使奇数位于偶数前面
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题21:调整数组顺序使奇数位于偶数前面
// 题目:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有
// 奇数位于数组的前半部分,所有偶数位于数组的后半部分。
#include <cstdio>
void Reorder(int *pData, unsigned int length, bool (*func)(int));
bool isEven(int n);
// ====================方法一====================
void ReorderOddEven_1(int *pData, unsigned int length)
{
if(pData == nullptr || length == 0)
return;
int *pBegin = pData;
int *pEnd = pData + length - 1;
while(pBegin < pEnd)
{
// 向后移动pBegin,直到它指向偶数
while(pBegin < pEnd && (*pBegin & 0x1) != 0)
pBegin ++;
// 向前移动pEnd,直到它指向奇数
while(pBegin < pEnd && (*pEnd & 0x1) == 0)
pEnd --;
if(pBegin < pEnd)
{
int temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
}
}
}
// ====================方法二====================
void ReorderOddEven_2(int *pData, unsigned int length)
{
Reorder(pData, length, isEven);
}
void Reorder(int *pData, unsigned int length, bool (*func)(int))
{
if(pData == nullptr || length == 0)
return;
int *pBegin = pData;
int *pEnd = pData + length - 1;
while(pBegin < pEnd)
{
// 向后移动pBegin
while(pBegin < pEnd && !func(*pBegin))
pBegin ++;
// 向前移动pEnd
while(pBegin < pEnd && func(*pEnd))
pEnd --;
if(pBegin < pEnd)
{
int temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
}
}
}
bool isEven(int n)
{
return (n & 1) == 0;
}
// ====================测试代码====================
void PrintArray(int numbers[], int length)
{
if(length < 0)
return;
for(int i = 0; i < length; ++i)
printf("%d\t", numbers[i]);
printf("\n");
}
void Test(char* testName, int numbers[], int length)
{
if(testName != nullptr)
printf("%s begins:\n", testName);
int* copy = new int[length];
for(int i = 0; i < length; ++i)
{
copy[i] = numbers[i];
}
printf("Test for solution 1:\n");
PrintArray(numbers, length);
ReorderOddEven_1(numbers, length);
PrintArray(numbers, length);
printf("Test for solution 2:\n");
PrintArray(copy, length);
ReorderOddEven_2(copy, length);
PrintArray(copy, length);
delete[] copy;
}
void Test1()
{
int numbers[] = {1, 2, 3, 4, 5, 6, 7};
Test("Test1", numbers, sizeof(numbers)/sizeof(int));
}
void Test2()
{
int numbers[] = {2, 4, 6, 1, 3, 5, 7};
Test("Test2", numbers, sizeof(numbers)/sizeof(int));
}
void Test3()
{
int numbers[] = {1, 3, 5, 7, 2, 4, 6};
Test("Test3", numbers, sizeof(numbers)/sizeof(int));
}
void Test4()
{
int numbers[] = {1};
Test("Test4", numbers, sizeof(numbers)/sizeof(int));
}
void Test5()
{
int numbers[] = {2};
Test("Test5", numbers, sizeof(numbers)/sizeof(int));
}
void Test6()
{
Test("Test6", nullptr, 0);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}
39. 面试题39:数组中出现次数超过一半的数字
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题39:数组中出现次数超过一半的数字
// 题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例
// 如输入一个长度为9的数组{1, 2, 3, 2, 2, 2, 5, 4, 2}。由于数字2在数组中
// 出现了5次,超过数组长度的一半,因此输出2。
#include <cstdio>
#include "..\Utilities\Array.h"
bool g_bInputInvalid = false;
bool CheckInvalidArray(int* numbers, int length)
{
g_bInputInvalid = false;
if(numbers == nullptr && length <= 0)
g_bInputInvalid = true;
return g_bInputInvalid;
}
bool CheckMoreThanHalf(int* numbers, int length, int number)
{
int times = 0;
for(int i = 0; i < length; ++i)
{
if(numbers[i] == number)
times++;
}
bool isMoreThanHalf = true;
if(times * 2 <= length)
{
g_bInputInvalid = true;
isMoreThanHalf = false;
}
return isMoreThanHalf;
}
// ====================方法1====================
int MoreThanHalfNum_Solution1(int* numbers, int length)
{
if(CheckInvalidArray(numbers, length))
return 0;
int middle = length >> 1;
int start = 0;
int end = length - 1;
int index = Partition(numbers, length, start, end);
while(index != middle)
{
if(index > middle)
{
end = index - 1;
index = Partition(numbers, length, start, end);
}
else
{
start = index + 1;
index = Partition(numbers, length, start, end);
}
}
int result = numbers[middle];
if(!CheckMoreThanHalf(numbers, length, result))
result = 0;
return result;
}
// ====================方法2====================
int MoreThanHalfNum_Solution2(int* numbers, int length)
{
if(CheckInvalidArray(numbers, length))
return 0;
int result = numbers[0];
int times = 1;
for(int i = 1; i < length; ++i)
{
if(times == 0)
{
result = numbers[i];
times = 1;
}
else if(numbers[i] == result)
times++;
else
times--;
}
if(!CheckMoreThanHalf(numbers, length, result))
result = 0;
return result;
}
// ====================测试代码====================
void Test(char* testName, int* numbers, int length, int expectedValue, bool expectedFlag)
{
if(testName != nullptr)
printf("%s begins: \n", testName);
int* copy = new int[length];
for(int i = 0; i < length; ++i)
copy[i] = numbers[i];
printf("Test for solution1: ");
int result = MoreThanHalfNum_Solution1(numbers, length);
if(result == expectedValue && g_bInputInvalid == expectedFlag)
printf("Passed.\n");
else
printf("Failed.\n");
printf("Test for solution2: ");
result = MoreThanHalfNum_Solution2(copy, length);
if(result == expectedValue && g_bInputInvalid == expectedFlag)
printf("Passed.\n");
else
printf("Failed.\n");
delete[] copy;
}
// 存在出现次数超过数组长度一半的数字
void Test1()
{
int numbers[] = {1, 2, 3, 2, 2, 2, 5, 4, 2};
Test("Test1", numbers, sizeof(numbers) / sizeof(int), 2, false);
}
// 不存在出现次数超过数组长度一半的数字
void Test2()
{
int numbers[] = {1, 2, 3, 2, 4, 2, 5, 2, 3};
Test("Test2", numbers, sizeof(numbers) / sizeof(int), 0, true);
}
// 出现次数超过数组长度一半的数字都出现在数组的前半部分
void Test3()
{
int numbers[] = {2, 2, 2, 2, 2, 1, 3, 4, 5};
Test("Test3", numbers, sizeof(numbers) / sizeof(int), 2, false);
}
// 出现次数超过数组长度一半的数字都出现在数组的后半部分
void Test4()
{
int numbers[] = {1, 3, 4, 5, 2, 2, 2, 2, 2};
Test("Test4", numbers, sizeof(numbers) / sizeof(int), 2, false);
}
// 输入空指针
void Test5()
{
int numbers[] = {1};
Test("Test5", numbers, 1, 1, false);
}
// 输入空指针
void Test6()
{
Test("Test6", nullptr, 0, 0, true);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}
42. 面试题42:连续子数组的最大和
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题42:连续子数组的最大和
// 题目:输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整
// 数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。
#include <cstdio>
bool g_InvalidInput = false;
int FindGreatestSumOfSubArray(int *pData, int nLength)
{
if((pData == nullptr) || (nLength <= 0))
{
g_InvalidInput = true;
return 0;
}
g_InvalidInput = false;
int nCurSum = 0;
int nGreatestSum = 0x80000000;
for(int i = 0; i < nLength; ++i)
{
if(nCurSum <= 0)
nCurSum = pData[i];
else
nCurSum += pData[i];
if(nCurSum > nGreatestSum)
nGreatestSum = nCurSum;
}
return nGreatestSum;
}
// ====================测试代码====================
void Test(char* testName, int* pData, int nLength, int expected, bool expectedFlag)
{
if(testName != nullptr)
printf("%s begins: \n", testName);
int result = FindGreatestSumOfSubArray(pData, nLength);
if(result == expected && expectedFlag == g_InvalidInput)
printf("Passed.\n");
else
printf("Failed.\n");
}
// 1, -2, 3, 10, -4, 7, 2, -5
void Test1()
{
int data[] = {1, -2, 3, 10, -4, 7, 2, -5};
Test("Test1", data, sizeof(data) / sizeof(int), 18, false);
}
// 所有数字都是负数
// -2, -8, -1, -5, -9
void Test2()
{
int data[] = {-2, -8, -1, -5, -9};
Test("Test2", data, sizeof(data) / sizeof(int), -1, false);
}
// 所有数字都是正数
// 2, 8, 1, 5, 9
void Test3()
{
int data[] = {2, 8, 1, 5, 9};
Test("Test3", data, sizeof(data) / sizeof(int), 25, false);
}
// 无效输入
void Test4()
{
Test("Test4", nullptr, 0, 0, true);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
return 0;
}
43. 面试题43:从1到n整数中1出现的次数
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题43:从1到n整数中1出现的次数
// 题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如
// 输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。
#include <cstdio>
#include <cstring>
#include <cstdlib>
// ====================方法一====================
int NumberOf1(unsigned int n);
int NumberOf1Between1AndN_Solution1(unsigned int n)
{
int number = 0;
for(unsigned int i = 1; i <= n; ++ i)
number += NumberOf1(i);
return number;
}
int NumberOf1(unsigned int n)
{
int number = 0;
while(n)
{
if(n % 10 == 1)
number ++;
n = n / 10;
}
return number;
}
// ====================方法二====================
int NumberOf1(const char* strN);
int PowerBase10(unsigned int n);
int NumberOf1Between1AndN_Solution2(int n)
{
if(n <= 0)
return 0;
char strN[50];
sprintf(strN, "%d", n);
return NumberOf1(strN);
}
int NumberOf1(const char* strN)
{
if(!strN || *strN < '0' || *strN > '9' || *strN == '\0')
return 0;
int first = *strN - '0';
unsigned int length = static_cast<unsigned int>(strlen(strN));
if(length == 1 && first == 0)
return 0;
if(length == 1 && first > 0)
return 1;
// 假设strN是"21345"
// numFirstDigit是数字10000-19999的第一个位中1的数目
int numFirstDigit = 0;
if(first > 1)
numFirstDigit = PowerBase10(length - 1);
else if(first == 1)
numFirstDigit = atoi(strN + 1) + 1;
// numOtherDigits是01346-21345除了第一位之外的数位中1的数目
int numOtherDigits = first * (length - 1) * PowerBase10(length - 2);
// numRecursive是1-1345中1的数目
int numRecursive = NumberOf1(strN + 1);
return numFirstDigit + numOtherDigits + numRecursive;
}
int PowerBase10(unsigned int n)
{
int result = 1;
for(unsigned int i = 0; i < n; ++ i)
result *= 10;
return result;
}
// ====================测试代码====================
void Test(const char* testName, int n, int expected)
{
if(testName != nullptr)
printf("%s begins: \n", testName);
if(NumberOf1Between1AndN_Solution1(n) == expected)
printf("Solution1 passed.\n");
else
printf("Solution1 failed.\n");
if(NumberOf1Between1AndN_Solution2(n) == expected)
printf("Solution2 passed.\n");
else
printf("Solution2 failed.\n");
printf("\n");
}
void Test()
{
Test("Test1", 1, 1);
Test("Test2", 5, 1);
Test("Test3", 10, 2);
Test("Test4", 55, 16);
Test("Test5", 99, 20);
Test("Test6", 10000, 4001);
Test("Test7", 21345, 18821);
Test("Test8", 0, 0);
}
int main(int argc, char* argv[])
{
Test();
return 0;
}
44. 面试题44:数字序列中某一位的数字
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题44:数字序列中某一位的数字
// 题目:数字以0123456789101112131415…的格式序列化到一个字符序列中。在这
// 个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。请写一
// 个函数求任意位对应的数字。
#include <iostream>
#include <algorithm>
using namespace std;
int countOfIntegers(int digits);
int digitAtIndex(int index, int digits);
int beginNumber(int digits);
int digitAtIndex(int index)
{
if(index < 0)
return -1;
int digits = 1;
while(true)
{
int numbers = countOfIntegers(digits);
if(index < numbers * digits)
return digitAtIndex(index, digits);
index -= digits * numbers;
digits++;
}
return -1;
}
int countOfIntegers(int digits)
{
if(digits == 1)
return 10;
int count = (int) std::pow(10, digits - 1);
return 9 * count;
}
int digitAtIndex(int index, int digits)
{
int number = beginNumber(digits) + index / digits;
int indexFromRight = digits - index % digits;
for(int i = 1; i < indexFromRight; ++i)
number /= 10;
return number % 10;
}
int beginNumber(int digits)
{
if(digits == 1)
return 0;
return (int) std::pow(10, digits - 1);
}
// ====================测试代码====================
void test(const char* testName, int inputIndex, int expectedOutput)
{
if(digitAtIndex(inputIndex) == expectedOutput)
cout << testName << " passed." << endl;
else
cout << testName << " FAILED." << endl;
}
int main()
{
test("Test1", 0, 0);
test("Test2", 1, 1);
test("Test3", 9, 9);
test("Test4", 10, 1);
test("Test5", 189, 9); // 数字99的最后一位,9
test("Test6", 190, 1); // 数字100的第一位,1
test("Test7", 1000, 3); // 数字370的第一位,3
test("Test8", 1001, 7); // 数字370的第二位,7
test("Test9", 1002, 0); // 数字370的第三位,0
return 0;
}
45. 面试题45:把数组排成最小的数
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题45:把数组排成最小的数
// 题目:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼
// 接出的所有数字中最小的一个。例如输入数组{3, 32, 321},则打印出这3个数
// 字能排成的最小数字321323。
#include "cstdio"
#include <string>
#include <algorithm>
int compare(const void* strNumber1, const void* strNumber2);
// int型整数用十进制表示最多只有10位
const int g_MaxNumberLength = 10;
char* g_StrCombine1 = new char[g_MaxNumberLength * 2 + 1];
char* g_StrCombine2 = new char[g_MaxNumberLength * 2 + 1];
void PrintMinNumber(const int* numbers, int length)
{
if(numbers == nullptr || length <= 0)
return;
char** strNumbers = (char**)(new int[length]);
for(int i = 0; i < length; ++i)
{
strNumbers[i] = new char[g_MaxNumberLength + 1];
sprintf(strNumbers[i], "%d", numbers[i]);
}
qsort(strNumbers, length, sizeof(char*), compare);
for(int i = 0; i < length; ++i)
printf("%s", strNumbers[i]);
printf("\n");
for(int i = 0; i < length; ++i)
delete[] strNumbers[i];
delete[] strNumbers;
}
// 如果[strNumber1][strNumber2] > [strNumber2][strNumber1], 返回值大于0
// 如果[strNumber1][strNumber2] = [strNumber2][strNumber1], 返回值等于0
// 如果[strNumber1][strNumber2] < [strNumber2][strNumber1], 返回值小于0
int compare(const void* strNumber1, const void* strNumber2)
{
// [strNumber1][strNumber2]
strcpy(g_StrCombine1, *(const char**)strNumber1);
strcat(g_StrCombine1, *(const char**)strNumber2);
// [strNumber2][strNumber1]
strcpy(g_StrCombine2, *(const char**)strNumber2);
strcat(g_StrCombine2, *(const char**)strNumber1);
return strcmp(g_StrCombine1, g_StrCombine2);
}
// ====================测试代码====================
void Test(const char* testName, int* numbers, int length, const char* expectedResult)
{
if(testName != nullptr)
printf("%s begins:\n", testName);
if(expectedResult != nullptr)
printf("Expected result is: \t%s\n", expectedResult);
printf("Actual result is: \t");
PrintMinNumber(numbers, length);
printf("\n");
}
void Test1()
{
int numbers[] = {3, 5, 1, 4, 2};
Test("Test1", numbers, sizeof(numbers)/sizeof(int), "12345");
}
void Test2()
{
int numbers[] = {3, 32, 321};
Test("Test2", numbers, sizeof(numbers)/sizeof(int), "321323");
}
void Test3()
{
int numbers[] = {3, 323, 32123};
Test("Test3", numbers, sizeof(numbers)/sizeof(int), "321233233");
}
void Test4()
{
int numbers[] = {1, 11, 111};
Test("Test4", numbers, sizeof(numbers)/sizeof(int), "111111");
}
// 数组中只有一个数字
void Test5()
{
int numbers[] = {321};
Test("Test5", numbers, sizeof(numbers)/sizeof(int), "321");
}
void Test6()
{
Test("Test6", nullptr, 0, "Don't print anything.");
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}
51. 面试题51:数组中的逆序对
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题51:数组中的逆序对
// 题目:在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组
// 成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
#include <cstdio>
int InversePairsCore(int* data, int* copy, int start, int end);
int InversePairs(int* data, int length)
{
if(data == nullptr || length < 0)
return 0;
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;
return count;
}
int InversePairsCore(int* data, int* copy, int start, int end)
{
if(start == end)
{
copy[start] = data[start];
return 0;
}
int length = (end - start) / 2;
int left = InversePairsCore(copy, data, start, start + length);
int right = InversePairsCore(copy, data, start + length + 1, end);
// i初始化为前半段最后一个数字的下标
int i = start + length;
// j初始化为后半段最后一个数字的下标
int j = end;
int indexCopy = end;
int count = 0;
while(i >= start && j >= start + length + 1)
{
if(data[i] > data[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 + 1; --j)
copy[indexCopy--] = data[j];
return left + right + count;
}
// ====================测试代码====================
void Test(char* testName, int* data, int length, int expected)
{
if(testName != nullptr)
printf("%s begins: ", testName);
if(InversePairs(data, length) == expected)
printf("Passed.\n");
else
printf("Failed.\n");
}
void Test1()
{
int data[] = { 1, 2, 3, 4, 7, 6, 5 };
int expected = 3;
Test("Test1", data, sizeof(data) / sizeof(int), expected);
}
// 递减排序数组
void Test2()
{
int data[] = { 6, 5, 4, 3, 2, 1 };
int expected = 15;
Test("Test2", data, sizeof(data) / sizeof(int), expected);
}
// 递增排序数组
void Test3()
{
int data[] = { 1, 2, 3, 4, 5, 6 };
int expected = 0;
Test("Test3", data, sizeof(data) / sizeof(int), expected);
}
// 数组中只有一个数字
void Test4()
{
int data[] = { 1 };
int expected = 0;
Test("Test4", data, sizeof(data) / sizeof(int), expected);
}
// 数组中只有两个数字,递增排序
void Test5()
{
int data[] = { 1, 2 };
int expected = 0;
Test("Test5", data, sizeof(data) / sizeof(int), expected);
}
// 数组中只有两个数字,递减排序
void Test6()
{
int data[] = { 2, 1 };
int expected = 1;
Test("Test6", data, sizeof(data) / sizeof(int), expected);
}
// 数组中有相等的数字
void Test7()
{
int data[] = { 1, 2, 1, 2, 1 };
int expected = 3;
Test("Test7", data, sizeof(data) / sizeof(int), expected);
}
void Test8()
{
int expected = 0;
Test("Test8", nullptr, 0, expected);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
return 0;
}
53. 面试题53:数字在排序数组中出现的次数
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题53(一):数字在排序数组中出现的次数
// 题目:统计一个数字在排序数组中出现的次数。例如输入排序数组{1, 2, 3, 3,
// 3, 3, 4, 5}和数字3,由于3在这个数组中出现了4次,因此输出4。
#include <cstdio>
int GetFirstK(const int* data, int length, int k, int start, int end);
int GetLastK(const int* data, int length, int k, int start, int end);
int GetNumberOfK(const int* data, int length, int k)
{
int number = 0;
if(data != nullptr && length > 0)
{
int first = GetFirstK(data, length, k, 0, length - 1);
int last = GetLastK(data, length, k, 0, length - 1);
if(first > -1 && last > -1)
number = last - first + 1;
}
return number;
}
// 找到数组中第一个k的下标。如果数组中不存在k,返回-1
int GetFirstK(const int* data, int length, int k, int start, int end)
{
if(start > end)
return -1;
int middleIndex = (start + end) / 2;
int middleData = data[middleIndex];
if(middleData == k)
{
if((middleIndex > 0 && data[middleIndex - 1] != k)
|| middleIndex == 0)
return middleIndex;
else
end = middleIndex - 1;
}
else if(middleData > k)
end = middleIndex - 1;
else
start = middleIndex + 1;
return GetFirstK(data, length, k, start, end);
}
// 找到数组中最后一个k的下标。如果数组中不存在k,返回-1
int GetLastK(const int* data, int length, int k, int start, int end)
{
if(start > end)
return -1;
int middleIndex = (start + end) / 2;
int middleData = data[middleIndex];
if(middleData == k)
{
if((middleIndex < length - 1 && data[middleIndex + 1] != k)
|| middleIndex == length - 1)
return middleIndex;
else
start = middleIndex + 1;
}
else if(middleData < k)
start = middleIndex + 1;
else
end = middleIndex - 1;
return GetLastK(data, length, k, start, end);
}
// ====================测试代码====================
void Test(const char* testName, int data[], int length, int k, int expected)
{
if(testName != nullptr)
printf("%s begins: ", testName);
int result = GetNumberOfK(data, length, k);
if(result == expected)
printf("Passed.\n");
else
printf("Failed.\n");
}
// 查找的数字出现在数组的中间
void Test1()
{
int data[] = {1, 2, 3, 3, 3, 3, 4, 5};
Test("Test1", data, sizeof(data) / sizeof(int), 3, 4);
}
// 查找的数组出现在数组的开头
void Test2()
{
int data[] = {3, 3, 3, 3, 4, 5};
Test("Test2", data, sizeof(data) / sizeof(int), 3, 4);
}
// 查找的数组出现在数组的结尾
void Test3()
{
int data[] = {1, 2, 3, 3, 3, 3};
Test("Test3", data, sizeof(data) / sizeof(int), 3, 4);
}
// 查找的数字不存在
void Test4()
{
int data[] = {1, 3, 3, 3, 3, 4, 5};
Test("Test4", data, sizeof(data) / sizeof(int), 2, 0);
}
// 查找的数字比第一个数字还小,不存在
void Test5()
{
int data[] = {1, 3, 3, 3, 3, 4, 5};
Test("Test5", data, sizeof(data) / sizeof(int), 0, 0);
}
// 查找的数字比最后一个数字还大,不存在
void Test6()
{
int data[] = {1, 3, 3, 3, 3, 4, 5};
Test("Test6", data, sizeof(data) / sizeof(int), 6, 0);
}
// 数组中的数字从头到尾都是查找的数字
void Test7()
{
int data[] = {3, 3, 3, 3};
Test("Test7", data, sizeof(data) / sizeof(int), 3, 4);
}
// 数组中的数字从头到尾只有一个重复的数字,不是查找的数字
void Test8()
{
int data[] = {3, 3, 3, 3};
Test("Test8", data, sizeof(data) / sizeof(int), 4, 0);
}
// 数组中只有一个数字,是查找的数字
void Test9()
{
int data[] = {3};
Test("Test9", data, sizeof(data) / sizeof(int), 3, 1);
}
// 数组中只有一个数字,不是查找的数字
void Test10()
{
int data[] = {3};
Test("Test10", data, sizeof(data) / sizeof(int), 4, 0);
}
// 鲁棒性测试,数组空指针
void Test11()
{
Test("Test11", nullptr, 0, 0, 0);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
Test11();
return 0;
}
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题53(二):0到n-1中缺失的数字
// 题目:一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字
// 都在范围0到n-1之内。在范围0到n-1的n个数字中有且只有一个数字不在该数组
// 中,请找出这个数字。
#include <cstdio>
int GetMissingNumber(const int* numbers, int length)
{
if(numbers == nullptr || length <= 0)
return -1;
int left = 0;
int right = length - 1;
while(left <= right)
{
int middle = (right + left) >> 1;
if(numbers[middle] != middle)
{
if(middle == 0 || numbers[middle - 1] == middle - 1)
return middle;
right = middle - 1;
}
else
left = middle + 1;
}
if(left == length)
return length;
// 无效的输入,比如数组不是按要求排序的,
// 或者有数字不在0到n-1范围之内
return -1;
}
// ====================测试代码====================
void Test(const char* testName, int numbers[], int length, int expected)
{
if(testName != nullptr)
printf("%s begins: ", testName);
int result = GetMissingNumber(numbers, length);
if(result == expected)
printf("Passed.\n");
else
printf("Failed.\n");
}
// 缺失的是第一个数字0
void Test1()
{
int numbers[] = { 1, 2, 3, 4, 5 };
int expected = 0;
Test("Test1", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 缺失的是最后一个数字
void Test2()
{
int numbers[] = { 0, 1, 2, 3, 4 };
int expected = 5;
Test("Test2", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 缺失的是中间某个数字0
void Test3()
{
int numbers[] = { 0, 1, 2, 4, 5 };
int expected = 3;
Test("Test3", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 数组中只有一个数字,缺失的是第一个数字0
void Test4()
{
int numbers[] = { 1 };
int expected = 0;
Test("Test4", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 数组中只有一个数字,缺失的是最后一个数字1
void Test5()
{
int numbers[] = { 0 };
int expected = 1;
Test("Test5", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 空数组
void Test6()
{
int expected = -1;
Test("Test6", nullptr, 0, expected);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题53(三):数组中数值和下标相等的元素
// 题目:假设一个单调递增的数组里的每个元素都是整数并且是唯一的。请编程实
// 现一个函数找出数组中任意一个数值等于其下标的元素。例如,在数组{-3, -1,
// 1, 3, 5}中,数字3和它的下标相等。
#include <cstdio>
int GetNumberSameAsIndex(const int* numbers, int length)
{
if(numbers == nullptr || length <= 0)
return -1;
int left = 0;
int right = length - 1;
while(left <= right)
{
int middle = left + ((right - left) >> 1);
if(numbers[middle] == middle)
return middle;
if(numbers[middle] > middle)
right = middle - 1;
else
left = middle + 1;
}
return -1;
}
// ====================测试代码====================
void Test(const char* testName, int numbers[], int length, int expected)
{
if(GetNumberSameAsIndex(numbers, length) == expected)
printf("%s passed.\n", testName);
else
printf("%s FAILED.\n", testName);
}
void Test1()
{
int numbers[] = { -3, -1, 1, 3, 5 };
int expected = 3;
Test("Test1", numbers, sizeof(numbers) / sizeof(int), expected);
}
void Test2()
{
int numbers[] = { 0, 1, 3, 5, 6 };
int expected = 0;
Test("Test2", numbers, sizeof(numbers) / sizeof(int), expected);
}
void Test3()
{
int numbers[] = { -1, 0, 1, 2, 4 };
int expected = 4;
Test("Test3", numbers, sizeof(numbers) / sizeof(int), expected);
}
void Test4()
{
int numbers[] = { -1, 0, 1, 2, 5 };
int expected = -1;
Test("Test4", numbers, sizeof(numbers) / sizeof(int), expected);
}
void Test5()
{
int numbers[] = { 0 };
int expected = 0;
Test("Test5", numbers, sizeof(numbers) / sizeof(int), expected);
}
void Test6()
{
int numbers[] = { 10 };
int expected = -1;
Test("Test6", numbers, sizeof(numbers) / sizeof(int), expected);
}
void Test7()
{
Test("Test7", nullptr, 0, -1);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
return 0;
}
56. 面试题56:数组中只出现一次的两个数字
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题56(一):数组中只出现一次的两个数字
// 题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序
// 找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
#include <cstdio>
unsigned int FindFirstBitIs1(int num);
bool IsBit1(int num, unsigned int indexBit);
void FindNumsAppearOnce(int data[], int length, int* num1, int* num2)
{
if(data == nullptr || length < 2)
return;
int resultExclusiveOR = 0;
for(int i = 0; i < length; ++i)
resultExclusiveOR ^= data[i];
unsigned int indexOf1 = FindFirstBitIs1(resultExclusiveOR);
*num1 = *num2 = 0;
for(int j = 0; j < length; ++j)
{
if(IsBit1(data[j], indexOf1))
*num1 ^= data[j];
else
*num2 ^= data[j];
}
}
// 找到num从右边数起第一个是1的位
unsigned int FindFirstBitIs1(int num)
{
int indexBit = 0;
while(((num & 1) == 0) && (indexBit < 8 * sizeof(int)))
{
num = num >> 1;
++indexBit;
}
return indexBit;
}
// 判断数字num的第indexBit位是不是1
bool IsBit1(int num, unsigned int indexBit)
{
num = num >> indexBit;
return (num & 1);
}
// ====================测试代码====================
void Test(const char* testName, int data[], int length, int expected1, int expected2)
{
if(testName != nullptr)
printf("%s begins: ", testName);
int result1, result2;
FindNumsAppearOnce(data, length, &result1, &result2);
if((expected1 == result1 && expected2 == result2) ||
(expected2 == result1 && expected1 == result2))
printf("Passed.\n\n");
else
printf("Failed.\n\n");
}
void Test1()
{
int data[] = { 2, 4, 3, 6, 3, 2, 5, 5 };
Test("Test1", data, sizeof(data) / sizeof(int), 4, 6);
}
void Test2()
{
int data[] = { 4, 6 };
Test("Test2", data, sizeof(data) / sizeof(int), 4, 6);
}
void Test3()
{
int data[] = { 4, 6, 1, 1, 1, 1 };
Test("Test3", data, sizeof(data) / sizeof(int), 4, 6);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
return 0;
}
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题56(二):数组中唯一只出现一次的数字
// 题目:在一个数组中除了一个数字只出现一次之外,其他数字都出现了三次。请
// 找出那个吃出现一次的数字。
#include <cstdio>
#include <exception>
int FindNumberAppearingOnce(int numbers[], int length)
{
if(numbers == nullptr || length <= 0)
throw new std::exception("Invalid input.");
int bitSum[32] = {0};
for(int i = 0; i < length; ++i)
{
int bitMask = 1;
for(int j = 31; j >= 0; --j)
{
int bit = numbers[i] & bitMask;
if(bit != 0)
bitSum[j] += 1;
bitMask = bitMask << 1;
}
}
int result = 0;
for(int i = 0; i < 32; ++i)
{
result = result << 1;
result += bitSum[i] % 3;
}
return result;
}
// ====================测试代码====================
void Test(const char* testName, int numbers[], int length, int expected)
{
int result = FindNumberAppearingOnce(numbers, length);
if(result == expected)
printf("%s passed.\n", testName);
else
printf("%s FAILED.\n", testName);
}
// 所有数字都是正数,唯一的数字是最小的
void Test1()
{
int numbers[] = { 1, 1, 2, 2, 2, 1, 3 };
int expected = 3;
Test("Test1", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 所有数字都是正数,唯一的数字的大小位于中间
void Test2()
{
int numbers[] = { 4, 3, 3, 2, 2, 2, 3 };
int expected = 4;
Test("Test2", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 所有数字都是正数,唯一的数字是最大的
void Test3()
{
int numbers[] = { 4, 4, 1, 1, 1, 7, 4 };
int expected = 7;
Test("Test3", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 唯一的数字是负数
void Test4()
{
int numbers[] = { -10, 214, 214, 214 };
int expected = -10;
Test("Test4", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 除了唯一的数字,其他数字都是负数
void Test5()
{
int numbers[] = { -209, 3467, -209, -209 };
int expected = 3467;
Test("Test5", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 重复的数字有正数也有负数
void Test6()
{
int numbers[] = { 1024, -1025, 1024, -1025, 1024, -1025, 1023 };
int expected = 1023;
Test("Test6", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 所有数字都是负数
void Test7()
{
int numbers[] = { -1024, -1024, -1024, -1023 };
int expected = -1023;
Test("Test7", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 唯一的数字是0
void Test8()
{
int numbers[] = { -23, 0, 214, -23, 214, -23, 214 };
int expected = 0;
Test("Test8", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 除了唯一的数字,其他数字都是0
void Test9()
{
int numbers[] = { 0, 3467, 0, 0, 0, 0, 0, 0 };
int expected = 3467;
Test("Test9", numbers, sizeof(numbers) / sizeof(int), expected);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
return 0;
}
57. 面试题57:和为s的两个数字
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题56(二):数组中唯一只出现一次的数字
// 题目:在一个数组中除了一个数字只出现一次之外,其他数字都出现了三次。请
// 找出那个吃出现一次的数字。
#include <cstdio>
#include <exception>
int FindNumberAppearingOnce(int numbers[], int length)
{
if(numbers == nullptr || length <= 0)
throw new std::exception("Invalid input.");
int bitSum[32] = {0};
for(int i = 0; i < length; ++i)
{
int bitMask = 1;
for(int j = 31; j >= 0; --j)
{
int bit = numbers[i] & bitMask;
if(bit != 0)
bitSum[j] += 1;
bitMask = bitMask << 1;
}
}
int result = 0;
for(int i = 0; i < 32; ++i)
{
result = result << 1;
result += bitSum[i] % 3;
}
return result;
}
// ====================测试代码====================
void Test(const char* testName, int numbers[], int length, int expected)
{
int result = FindNumberAppearingOnce(numbers, length);
if(result == expected)
printf("%s passed.\n", testName);
else
printf("%s FAILED.\n", testName);
}
// 所有数字都是正数,唯一的数字是最小的
void Test1()
{
int numbers[] = { 1, 1, 2, 2, 2, 1, 3 };
int expected = 3;
Test("Test1", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 所有数字都是正数,唯一的数字的大小位于中间
void Test2()
{
int numbers[] = { 4, 3, 3, 2, 2, 2, 3 };
int expected = 4;
Test("Test2", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 所有数字都是正数,唯一的数字是最大的
void Test3()
{
int numbers[] = { 4, 4, 1, 1, 1, 7, 4 };
int expected = 7;
Test("Test3", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 唯一的数字是负数
void Test4()
{
int numbers[] = { -10, 214, 214, 214 };
int expected = -10;
Test("Test4", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 除了唯一的数字,其他数字都是负数
void Test5()
{
int numbers[] = { -209, 3467, -209, -209 };
int expected = 3467;
Test("Test5", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 重复的数字有正数也有负数
void Test6()
{
int numbers[] = { 1024, -1025, 1024, -1025, 1024, -1025, 1023 };
int expected = 1023;
Test("Test6", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 所有数字都是负数
void Test7()
{
int numbers[] = { -1024, -1024, -1024, -1023 };
int expected = -1023;
Test("Test7", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 唯一的数字是0
void Test8()
{
int numbers[] = { -23, 0, 214, -23, 214, -23, 214 };
int expected = 0;
Test("Test8", numbers, sizeof(numbers) / sizeof(int), expected);
}
// 除了唯一的数字,其他数字都是0
void Test9()
{
int numbers[] = { 0, 3467, 0, 0, 0, 0, 0, 0 };
int expected = 3467;
Test("Test9", numbers, sizeof(numbers) / sizeof(int), expected);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
return 0;
}
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题57(二):为s的连续正数序列
// 题目:输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。
// 例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以结果打印出3个连续序列1~5、
// 4~6和7~8。
#include <cstdio>
void PrintContinuousSequence(int small, int big);
void FindContinuousSequence(int sum)
{
if(sum < 3)
return;
int small = 1;
int big = 2;
int middle = (1 + sum) / 2;
int curSum = small + big;
while(small < middle)
{
if(curSum == sum)
PrintContinuousSequence(small, big);
while(curSum > sum && small < middle)
{
curSum -= small;
small ++;
if(curSum == sum)
PrintContinuousSequence(small, big);
}
big ++;
curSum += big;
}
}
void PrintContinuousSequence(int small, int big)
{
for(int i = small; i <= big; ++ i)
printf("%d ", i);
printf("\n");
}
// ====================测试代码====================
void Test(const char* testName, int sum)
{
if(testName != nullptr)
printf("%s for %d begins: \n", testName, sum);
FindContinuousSequence(sum);
}
int main(int argc, char* argv[])
{
Test("test1", 1);
Test("test2", 3);
Test("test3", 4);
Test("test4", 9);
Test("test5", 15);
Test("test6", 100);
return 0;
}
58. 面试题58:翻转单词顺序
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题58(一):翻转单词顺序
// 题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
// 为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",
// 则输出"student. a am I"。
#include <cstdio>
#include "..\Utilities\StringUtil.h"
#include <string>
char* ReverseSentence(char *pData)
{
if(pData == nullptr)
return nullptr;
char *pBegin = pData;
char *pEnd = pData;
while(*pEnd != '\0')
pEnd ++;
pEnd--;
// 翻转整个句子
Reverse(pBegin, pEnd);
// 翻转句子中的每个单词
pBegin = pEnd = pData;
while(*pBegin != '\0')
{
if(*pBegin == ' ')
{
pBegin ++;
pEnd ++;
}
else if(*pEnd == ' ' || *pEnd == '\0')
{
Reverse(pBegin, --pEnd);
pBegin = ++pEnd;
}
else
pEnd ++;
}
return pData;
}
// ====================测试代码====================
void Test(const char* testName, char* input, const char* expectedResult)
{
if(testName != nullptr)
printf("%s begins: ", testName);
ReverseSentence(input);
if((input == nullptr && expectedResult == nullptr)
|| (input != nullptr && strcmp(input, expectedResult) == 0))
printf("Passed.\n\n");
else
printf("Failed.\n\n");
}
// 功能测试,句子中有多个单词
void Test1()
{
char input[] = "I am a student.";
char expected[] = "student. a am I";
Test("Test1", input, expected);
}
// 功能测试,句子中只有一个单词
void Test2()
{
char input[] = "Wonderful";
char expected[] = "Wonderful";
Test("Test2", input, expected);
}
// 鲁棒性测试
void Test3()
{
Test("Test3", nullptr, nullptr);
}
// 边界值测试,测试空字符串
void Test4()
{
Test("Test4", "", "");
}
// 边界值测试,字符串中只有空格
void Test5()
{
char input[] = " ";
char expected[] = " ";
Test("Test5", input, expected);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
return 0;
}
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题58(二):左旋转字符串
// 题目:字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
// 请定义一个函数实现字符串左旋转操作的功能。比如输入字符串"abcdefg"和数
// 字2,该函数将返回左旋转2位得到的结果"cdefgab"。
#include <cstdio>
#include "..\Utilities\StringUtil.h"
#include <string.h>
char* LeftRotateString(char* pStr, int n)
{
if(pStr != nullptr)
{
int nLength = static_cast<int>(strlen(pStr));
if(nLength > 0 && n > 0 && n < nLength)
{
char* pFirstStart = pStr;
char* pFirstEnd = pStr + n - 1;
char* pSecondStart = pStr + n;
char* pSecondEnd = pStr + nLength - 1;
// 翻转字符串的前面n个字符
Reverse(pFirstStart, pFirstEnd);
// 翻转字符串的后面部分
Reverse(pSecondStart, pSecondEnd);
// 翻转整个字符串
Reverse(pFirstStart, pSecondEnd);
}
}
return pStr;
}
// ====================测试代码====================
void Test(const char* testName, char* input, int num, const char* expectedResult)
{
if(testName != nullptr)
printf("%s begins: ", testName);
char* result = LeftRotateString(input, num);
if((input == nullptr && expectedResult == nullptr)
|| (input != nullptr && strcmp(result, expectedResult) == 0))
printf("Passed.\n\n");
else
printf("Failed.\n\n");
}
// 功能测试
void Test1()
{
char input[] = "abcdefg";
char expected[] = "cdefgab";
Test("Test1", input, 2, expected);
}
// 边界值测试
void Test2()
{
char input[] = "abcdefg";
char expected[] = "bcdefga";
Test("Test2", input, 1, expected);
}
// 边界值测试
void Test3()
{
char input[] = "abcdefg";
char expected[] = "gabcdef";
Test("Test3", input, 6, expected);
}
// 鲁棒性测试
void Test4()
{
Test("Test4", nullptr, 6, nullptr);
}
// 鲁棒性测试
void Test5()
{
char input[] = "abcdefg";
char expected[] = "abcdefg";
Test("Test5", input, 0, expected);
}
// 鲁棒性测试
void Test6()
{
char input[] = "abcdefg";
char expected[] = "abcdefg";
Test("Test6", input, 7, expected);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}
59. 面试题59:滑动窗口的最大值
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题59(一):滑动窗口的最大值
// 题目:给定一个数组和滑动窗口的大小,请找出所有滑动窗口里的最大值。例如,
// 如果输入数组{2, 3, 4, 2, 6, 2, 5, 1}及滑动窗口的大小3,那么一共存在6个
// 滑动窗口,它们的最大值分别为{4, 4, 6, 6, 6, 5},
#include <cstdio>
#include <vector>
#include <deque>
using namespace std;
vector<int> maxInWindows(const vector<int>& num, unsigned int size)
{
vector<int> maxInWindows;
if(num.size() >= size && size >= 1)
{
deque<int> index;
for(unsigned int i = 0; i < size; ++i)
{
while(!index.empty() && num[i] >= num[index.back()])
index.pop_back();
index.push_back(i);
}
for(unsigned int i = size; i < num.size(); ++i)
{
maxInWindows.push_back(num[index.front()]);
while(!index.empty() && num[i] >= num[index.back()])
index.pop_back();
if(!index.empty() && index.front() <= (int) (i - size))
index.pop_front();
index.push_back(i);
}
maxInWindows.push_back(num[index.front()]);
}
return maxInWindows;
}
// ====================测试代码====================
void Test(const char* testName, const vector<int>& num, unsigned int size, const vector<int>& expected)
{
if(testName != nullptr)
printf("%s begins: ", testName);
vector<int> result = maxInWindows(num, size);
vector<int>::const_iterator iterResult = result.begin();
vector<int>::const_iterator iterExpected = expected.begin();
while(iterResult < result.end() && iterExpected < expected.end())
{
if(*iterResult != *iterExpected)
break;
++iterResult;
++iterExpected;
}
if(iterResult == result.end() && iterExpected == expected.end())
printf("Passed.\n");
else
printf("FAILED.\n");
}
void Test1()
{
int num[] = { 2, 3, 4, 2, 6, 2, 5, 1 };
vector<int> vecNumbers(num, num + sizeof(num) / sizeof(int));
int expected[] = { 4, 4, 6, 6, 6, 5 };
vector<int> vecExpected(expected, expected + sizeof(expected) / sizeof(int));
unsigned int size = 3;
Test("Test1", vecNumbers, size, vecExpected);
}
void Test2()
{
int num[] = { 1, 3, -1, -3, 5, 3, 6, 7 };
vector<int> vecNumbers(num, num + sizeof(num) / sizeof(int));
int expected[] = { 3, 3, 5, 5, 6, 7 };
vector<int> vecExpected(expected, expected + sizeof(expected) / sizeof(int));
unsigned int size = 3;
Test("Test2", vecNumbers, size, vecExpected);
}
// 输入数组单调递增
void Test3()
{
int num[] = { 1, 3, 5, 7, 9, 11, 13, 15 };
vector<int> vecNumbers(num, num + sizeof(num) / sizeof(int));
int expected[] = { 7, 9, 11, 13, 15 };
vector<int> vecExpected(expected, expected + sizeof(expected) / sizeof(int));
unsigned int size = 4;
Test("Test3", vecNumbers, size, vecExpected);
}
// 输入数组单调递减
void Test4()
{
int num[] = { 16, 14, 12, 10, 8, 6, 4 };
vector<int> vecNumbers(num, num + sizeof(num) / sizeof(int));
int expected[] = { 16, 14, 12 };
vector<int> vecExpected(expected, expected + sizeof(expected) / sizeof(int));
unsigned int size = 5;
Test("Test4", vecNumbers, size, vecExpected);
}
// 滑动窗口的大小为1
void Test5()
{
int num[] = { 10, 14, 12, 11 };
vector<int> vecNumbers(num, num + sizeof(num) / sizeof(int));
int expected[] = { 10, 14, 12, 11 };
vector<int> vecExpected(expected, expected + sizeof(expected) / sizeof(int));
unsigned int size = 1;
Test("Test5", vecNumbers, size, vecExpected);
}
// 滑动窗口的大小等于数组的长度
void Test6()
{
int num[] = { 10, 14, 12, 11 };
vector<int> vecNumbers(num, num + sizeof(num) / sizeof(int));
int expected[] = { 14 };
vector<int> vecExpected(expected, expected + sizeof(expected) / sizeof(int));
unsigned int size = 4;
Test("Test6", vecNumbers, size, vecExpected);
}
// 滑动窗口的大小为0
void Test7()
{
int num[] = { 10, 14, 12, 11 };
vector<int> vecNumbers(num, num + sizeof(num) / sizeof(int));
vector<int> vecExpected;
unsigned int size = 0;
Test("Test7", vecNumbers, size, vecExpected);
}
// 滑动窗口的大小大于输入数组的长度
void Test8()
{
int num[] = { 10, 14, 12, 11 };
vector<int> vecNumbers(num, num + sizeof(num) / sizeof(int));
vector<int> vecExpected;
unsigned int size = 5;
Test("Test8", vecNumbers, size, vecExpected);
}
// 输入数组为空
void Test9()
{
vector<int> vecNumbers;
vector<int> vecExpected;
unsigned int size = 5;
Test("Test9", vecNumbers, size, vecExpected);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
return 0;
}
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题59(二):队列的最大值
// 题目:给定一个数组和滑动窗口的大小,请找出所有滑动窗口里的最大值。例如,
// 如果输入数组{2, 3, 4, 2, 6, 2, 5, 1}及滑动窗口的大小3,那么一共存在6个
// 滑动窗口,它们的最大值分别为{4, 4, 6, 6, 6, 5},
#include <cstdio>
#include <deque>
#include <exception>
using namespace std;
template<typename T> class QueueWithMax
{
public:
QueueWithMax() : currentIndex(0)
{
}
void push_back(T number)
{
while(!maximums.empty() && number >= maximums.back().number)
maximums.pop_back();
InternalData internalData = { number, currentIndex };
data.push_back(internalData);
maximums.push_back(internalData);
++currentIndex;
}
void pop_front()
{
if(maximums.empty())
throw new exception("queue is empty");
if(maximums.front().index == data.front().index)
maximums.pop_front();
data.pop_front();
}
T max() const
{
if(maximums.empty())
throw new exception("queue is empty");
return maximums.front().number;
}
private:
struct InternalData
{
T number;
int index;
};
deque<InternalData> data;
deque<InternalData> maximums;
int currentIndex;
};
// ====================测试代码====================
void Test(const char* testName, const QueueWithMax<int>& queue, int expected)
{
if(testName != nullptr)
printf("%s begins: ", testName);
if(queue.max() == expected)
printf("Passed.\n");
else
printf("FAILED.\n");
}
int main(int argc, char* argv[])
{
QueueWithMax<int> queue;
// {2}
queue.push_back(2);
Test("Test1", queue, 2);
// {2, 3}
queue.push_back(3);
Test("Test2", queue, 3);
// {2, 3, 4}
queue.push_back(4);
Test("Test3", queue, 4);
// {2, 3, 4, 2}
queue.push_back(2);
Test("Test4", queue, 4);
// {3, 4, 2}
queue.pop_front();
Test("Test5", queue, 4);
// {4, 2}
queue.pop_front();
Test("Test6", queue, 4);
// {2}
queue.pop_front();
Test("Test7", queue, 2);
// {2, 6}
queue.push_back(6);
Test("Test8", queue, 6);
// {2, 6, 2}
queue.push_back(2);
Test("Test9", queue, 6);
// {2, 6, 2, 5}
queue.push_back(5);
Test("Test9", queue, 6);
// {6, 2, 5}
queue.pop_front();
Test("Test10", queue, 6);
// {2, 5}
queue.pop_front();
Test("Test11", queue, 5);
// {5}
queue.pop_front();
Test("Test12", queue, 5);
// {5, 1}
queue.push_back(1);
Test("Test13", queue, 5);
return 0;
}
60. 面试题60:n个骰子的点数
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题60:n个骰子的点数
// 题目:把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s
// 的所有可能的值出现的概率。
#include <cstdio>
#include <math.h>
int g_maxValue = 6;
// ====================方法一====================
void Probability(int number, int* pProbabilities);
void Probability(int original, int current, int sum, int* pProbabilities);
void PrintProbability_Solution1(int number)
{
if(number < 1)
return;
int maxSum = number * g_maxValue;
int* pProbabilities = new int[maxSum - number + 1];
for(int i = number; i <= maxSum; ++i)
pProbabilities[i - number] = 0;
Probability(number, pProbabilities);
int total = pow((double)g_maxValue, number);
for(int i = number; i <= maxSum; ++i)
{
double ratio = (double)pProbabilities[i - number] / total;
printf("%d: %e\n", i, ratio);
}
delete[] pProbabilities;
}
void Probability(int number, int* pProbabilities)
{
for(int i = 1; i <= g_maxValue; ++i)
Probability(number, number, i, pProbabilities);
}
void Probability(int original, int current, int sum,
int* pProbabilities)
{
if(current == 1)
{
pProbabilities[sum - original]++;
}
else
{
for(int i = 1; i <= g_maxValue; ++i)
{
Probability(original, current - 1, i + sum, pProbabilities);
}
}
}
// ====================方法二====================
void PrintProbability_Solution2(int number)
{
if(number < 1)
return;
int* pProbabilities[2];
pProbabilities[0] = new int[g_maxValue * number + 1];
pProbabilities[1] = new int[g_maxValue * number + 1];
for(int i = 0; i < g_maxValue * number + 1; ++i)
{
pProbabilities[0][i] = 0;
pProbabilities[1][i] = 0;
}
int flag = 0;
for (int i = 1; i <= g_maxValue; ++i)
pProbabilities[flag][i] = 1;
for (int k = 2; k <= number; ++k)
{
for(int i = 0; i < k; ++i)
pProbabilities[1 - flag][i] = 0;
for (int i = k; i <= g_maxValue * k; ++i)
{
pProbabilities[1 - flag][i] = 0;
for(int j = 1; j <= i && j <= g_maxValue; ++j)
pProbabilities[1 - flag][i] += pProbabilities[flag][i - j];
}
flag = 1 - flag;
}
double total = pow((double)g_maxValue, number);
for(int i = number; i <= g_maxValue * number; ++i)
{
double ratio = (double)pProbabilities[flag][i] / total;
printf("%d: %e\n", i, ratio);
}
delete[] pProbabilities[0];
delete[] pProbabilities[1];
}
// ====================测试代码====================
void Test(int n)
{
printf("Test for %d begins:\n", n);
printf("Test for solution1\n");
PrintProbability_Solution1(n);
printf("Test for solution2\n");
PrintProbability_Solution2(n);
printf("\n");
}
int main(int argc, char* argv[])
{
Test(1);
Test(2);
Test(3);
Test(4);
Test(11);
Test(0);
return 0;
}
61. 面试题61:扑克牌的顺子
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题61:扑克牌的顺子
// 题目:从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。
// 2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王可以看成任意数字。
#include <cstdio>
#include <cstdlib>
int Compare(const void *arg1, const void *arg2);
bool IsContinuous(int* numbers, int length)
{
if(numbers == nullptr || length < 1)
return false;
qsort(numbers, length, sizeof(int), Compare);
int numberOfZero = 0;
int numberOfGap = 0;
// 统计数组中0的个数
for(int i = 0; i < length && numbers[i] == 0; ++i)
++numberOfZero;
// 统计数组中的间隔数目
int small = numberOfZero;
int big = small + 1;
while(big < length)
{
// 两个数相等,有对子,不可能是顺子
if(numbers[small] == numbers[big])
return false;
numberOfGap += numbers[big] - numbers[small] - 1;
small = big;
++big;
}
return (numberOfGap > numberOfZero) ? false : true;
}
int Compare(const void *arg1, const void *arg2)
{
return *(int*) arg1 - *(int*) arg2;
}
// ====================测试代码====================
void Test(const char* testName, int* numbers, int length, bool expected)
{
if(testName != nullptr)
printf("%s begins: ", testName);
if(IsContinuous(numbers, length) == expected)
printf("Passed.\n");
else
printf("Failed.\n");
}
void Test1()
{
int numbers[] = { 1, 3, 2, 5, 4 };
Test("Test1", numbers, sizeof(numbers) / sizeof(int), true);
}
void Test2()
{
int numbers[] = { 1, 3, 2, 6, 4 };
Test("Test2", numbers, sizeof(numbers) / sizeof(int), false);
}
void Test3()
{
int numbers[] = { 0, 3, 2, 6, 4 };
Test("Test3", numbers, sizeof(numbers) / sizeof(int), true);
}
void Test4()
{
int numbers[] = { 0, 3, 1, 6, 4 };
Test("Test4", numbers, sizeof(numbers) / sizeof(int), false);
}
void Test5()
{
int numbers[] = { 1, 3, 0, 5, 0 };
Test("Test5", numbers, sizeof(numbers) / sizeof(int), true);
}
void Test6()
{
int numbers[] = { 1, 3, 0, 7, 0 };
Test("Test6", numbers, sizeof(numbers) / sizeof(int), false);
}
void Test7()
{
int numbers[] = { 1, 0, 0, 5, 0 };
Test("Test7", numbers, sizeof(numbers) / sizeof(int), true);
}
62. 面试题62:圆圈中最后剩下的数字
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题62:圆圈中最后剩下的数字
// 题目:0, 1, …, n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里
// 删除第m个数字。求出这个圆圈里剩下的最后一个数字。
#include <cstdio>
#include <list>
using namespace std;
// ====================方法1====================
int LastRemaining_Solution1(unsigned int n, unsigned int m)
{
if(n < 1 || m < 1)
return -1;
unsigned int i = 0;
list<int> numbers;
for(i = 0; i < n; ++ i)
numbers.push_back(i);
list<int>::iterator current = numbers.begin();
while(numbers.size() > 1)
{
for(int i = 1; i < m; ++ i)
{
current ++;
if(current == numbers.end())
current = numbers.begin();
}
list<int>::iterator next = ++ current;
if(next == numbers.end())
next = numbers.begin();
-- current;
numbers.erase(current);
current = next;
}
return *(current);
}
// ====================方法2====================
int LastRemaining_Solution2(unsigned int n, unsigned int m)
{
if(n < 1 || m < 1)
return -1;
int last = 0;
for (int i = 2; i <= n; i ++)
last = (last + m) % i;
return last;
}
// ====================测试代码====================
void Test(const char* testName, unsigned int n, unsigned int m, int expected)
{
if(testName != nullptr)
printf("%s begins: \n", testName);
if(LastRemaining_Solution1(n, m) == expected)
printf("Solution1 passed.\n");
else
printf("Solution1 failed.\n");
if(LastRemaining_Solution2(n, m) == expected)
printf("Solution2 passed.\n");
else
printf("Solution2 failed.\n");
printf("\n");
}
void Test1()
{
Test("Test1", 5, 3, 3);
}
void Test2()
{
Test("Test2", 5, 2, 2);
}
void Test3()
{
Test("Test3", 6, 7, 4);
}
void Test4()
{
Test("Test4", 6, 6, 3);
}
void Test5()
{
Test("Test5", 0, 0, -1);
}
void Test6()
{
Test("Test6", 4000, 997, 1027);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}
66. 面试题66:构建乘积数组
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题66:构建乘积数组
// 题目:给定一个数组A[0, 1, …, n-1],请构建一个数组B[0, 1, …, n-1],其
// 中B中的元素B[i] =A[0]×A[1]×… ×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。
#include <cstdio>
#include <vector>
using namespace std;
void BuildProductionArray(const vector<double>& input, vector<double>& output)
{
int length1 = input.size();
int length2 = output.size();
if(length1 == length2 && length2 > 1)
{
output[0] = 1;
for(int i = 1; i < length1; ++i)
{
output[i] = output[i - 1] * input[i - 1];
}
double temp = 1;
for(int i = length1 - 2; i >= 0; --i)
{
temp *= input[i + 1];
output[i] *= temp;
}
}
}
//================= Test Code =================
static bool EqualArrays(const vector<double>& input, const vector<double>& output)
{
int length1 = input.size();
int length2 = output.size();
if(length1 != length2)
return false;
for(int i = 0; i < length1; ++i)
{
if(abs(input[i] - output[i]) > 0.0000001)
return false;
}
return true;
}
static void test(char* testName, const vector<double>& input, vector<double>& output, const vector<double>& expected)
{
printf("%s Begins: ", testName);
BuildProductionArray(input, output);
if(EqualArrays(output, expected))
printf("Passed.\n");
else
printf("FAILED.\n");
}
static void test1()
{
// 输入数组中没有0
double input[] = { 1, 2, 3, 4, 5 };
double output[] = { 0, 0, 0, 0, 0 };
double expected[] = { 120, 60, 40, 30, 24 };
test("Test1", vector<double>(input, input + sizeof(input) / sizeof(double)),
vector<double>(output, output + sizeof(output) / sizeof(double)),
vector<double>(expected, expected + sizeof(expected) / sizeof(double)));
}
static void test2()
{
// 输入数组中有一个0
double input[] = { 1, 2, 0, 4, 5 };
double output[] = { 0, 0, 0, 0, 0 };
double expected[] = { 0, 0, 40, 0, 0 };
test("Test2", vector<double>(input, input + sizeof(input) / sizeof(double)),
vector<double>(output, output + sizeof(output) / sizeof(double)),
vector<double>(expected, expected + sizeof(expected) / sizeof(double)));
}
static void test3()
{
// 输入数组中有两个0
double input[] = { 1, 2, 0, 4, 0 };
double output[] = { 0, 0, 0, 0, 0 };
double expected[] = { 0, 0, 0, 0, 0 };
test("Test3", vector<double>(input, input + sizeof(input) / sizeof(double)),
vector<double>(output, output + sizeof(output) / sizeof(double)),
vector<double>(expected, expected + sizeof(expected) / sizeof(double)));
}
static void test4()
{
// 输入数组中有正、负数
double input[] = { 1, -2, 3, -4, 5 };
double output[] = { 0, 0, 0, 0, 0 };
double expected[] = { 120, -60, 40, -30, 24 };
test("Test4", vector<double>(input, input + sizeof(input) / sizeof(double)),
vector<double>(output, output + sizeof(output) / sizeof(double)),
vector<double>(expected, expected + sizeof(expected) / sizeof(double)));
}
static void test5()
{
// 输入输入中只有两个数字
double input[] = { 1, -2 };
double output[] = { 0, 0 };
double expected[] = { -2, 1 };
test("Test5", vector<double>(input, input + sizeof(input) / sizeof(double)),
vector<double>(output, output + sizeof(output) / sizeof(double)),
vector<double>(expected, expected + sizeof(expected) / sizeof(double)));
}
int main(int argc, char* argv[])
{
test1();
test2();
test3();
test4();
test5();
return 0;
}