day19-day21代码片段

1. 1-n中某数字出现的次数

#include<iostream>
using namespace std;
int getNum(int n, int k)
{
    int x;
    int count = 0;
    if (n == 0 && k == 0)
        return 1;
    for (int i = 1; x=n/ i; i *= 10)
    {
        int high = x / 10;
        if (k == 0)
        {
            if (high)
                high--;
            else
            {
                count++;
                break;
            }
        }
        count += high*i;
        int current = x % 10;
        if (current > k)
            count += i;
        else if (current == k)
            count += n - x*i + 1;
    }
    return count;
}
int main()
{
    int n;
    while (cin >> n)
        cout << getNum(n,1) << endl;
    return 0;
}

2. 数组中最小的K个数

#include<iostream>
using namespace std;
int partion(int *arr, int left, int right)
{
    int start = left;
    int end = right;
    int key = arr[left];
    while (start < end)
    {
        while (start<end&&arr[end]>=key)
            --end;
        while (start < end&&arr[start] <= key)
            ++start;
        swap(arr[end], arr[start]);
    }
    swap(arr[left], arr[start]);
    return start;
}
void getArr(int *arr, int len, int k, int *res)
{
    int end = len - 1;
    int start = 0;
    int index = partion(arr, start, end);
    while (index != k - 1)
    {
        if (index > k - 1)
        {
            end = index - 1;
            index = partion(arr, start, end);
        }
        else
        {
            start = index + 1;
            index = partion(arr, start, end);
        }
    }
    for (int i = 0; i < k; i++)
        res[i] = arr[i];
}
void GetLength(int *arr, int len, int k)
{
    if (arr == nullptr || len <= 0 || k <= 0 || k >len)
        return;
    int *res = new int[k];
    getArr(arr, len, k, res);
    for (int i = 0; i < k; i++)
    {
        cout << res[i] << " ";
    }
    cout << endl;
}
int main()
{
    int arr[] = { 1, 2, 3, 65, 0,5, 7, 43, 2 };
    int len = sizeof(arr) / sizeof(arr[0]);
    int k;
    while (cin>>k)
        GetLength(arr, len,k);
}

3. 连续子数组的最大和

#include<iostream>
using namespace std;
int getMax(int *arr, int len)
{
    int max = 0;
    int sum = 0;
    for (int i = 0; i < len; i++)
    {
        sum += arr[i];
        if (sum>max)
            max = sum;
        else if (sum <0)
            sum = 0;
    }
    return max;
}
int main()
{
    int arr[] = { 1, -2, 3, 10, -4, 7, 2, -5 };
    int len = sizeof(arr) / sizeof(arr[0]);
    cout << getMax(arr, len) << endl;
    system("pause");
}

4. 数字序列中某一位的数字

// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================

// 面试题44:数字序列中某一位的数字
// 题目:数字以0123456789101112131415…的格式序列化到一个字符序列中。在这
// 个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。请写一
// 个函数求任意位对应的数字。
#include<iostream>
using namespace std;
int countOfIntergers(int digits)
{
    if (digits == 1)
        return 10;
    int count = (int)pow(10, digits - 1);
    return 9 * count;
}
int beginNumber(int digits)
{
    if (digits == 1)
        return 0;
    return (int)pow(10, digits - 1);
}
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 digitAtIndex(int index)
{
    if (index < 0)
        return -1;
    int digits = 1;
    for (;;)
    {
        int numbers = countOfIntergers(digits);
        if (index < numbers*digits)
            return digitAtIndex(index, digits);
        index -= digits*numbers;
        digits++;

    }
    return -1;
}
int main()
{
    int n;
    while (cin >> n)
        cout << digitAtIndex(n) << endl;s
}

5. 把数字数组排成最小的数

// 面试题45:把数组排成最小的数
// 题目:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼
// 接出的所有数字中最小的一个。例如输入数组{3, 32, 321},则打印出这3个数
// 字能排成的最小数字321323。
#include<iostream>
using namespace std;
const int g_MaxNumberLength = 10;
char *comb1 = new char[g_MaxNumberLength * 2 + 1];
char *comb2 = new char[g_MaxNumberLength * 2 + 1];
int compare(const void *strNumber1, const void *strNumber2)
{
    strcpy(comb1, *(const char **)strNumber1);
    strcat(comb1, *(const char **)strNumber2);
    strcpy(comb2, *(const char **)strNumber2);
    strcat(comb2, *(const char **)strNumber1);
    return strcmp(comb1, comb2);
}
void PrintMinNumber(int *arr, int length)
{
    if (arr == 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", arr[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;
}

6. 把数字翻译成字符串

/*******************************************************************
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——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================

// 面试题46:把数字翻译成字符串
// 题目:给定一个数字,我们按照如下规则把它翻译为字符串:0翻译成"a",1翻
// 译成"b",……,11翻译成"l",……,25翻译成"z"。一个数字可能有多个翻译。例
// 如12258有5种不同的翻译,它们分别是"bccfi"、"bwfi"、"bczi"、"mcfi"和
// "mzi"。请编程实现一个函数用来计算一个数字有多少种不同的翻译方法。

#include <string>
#include <iostream>

using namespace std;

int GetTranslationCount(const string& number);

int GetTranslationCount(int number)
{
    if(number < 0)
        return 0;

    string numberInString = to_string(number);
    return GetTranslationCount(numberInString);
}

int GetTranslationCount(const string& number)
{
    int length = number.length();
    int* counts = new int[length];
    int count = 0;

    for(int i = length - 1; i >= 0; --i)
    {
        count = 0;
         if(i < length - 1)
               count = counts[i + 1];
         else
               count = 1;

        if(i < length - 1)
        {
            int digit1 = number[i] - '0';
            int digit2 = number[i + 1] - '0';
            int converted = digit1 * 10 + digit2;
            if(converted >= 10 && converted <= 25)
            {
                if(i < length - 2)
                    count += counts[i + 2];
                else
                    count += 1;
            }
        }

        counts[i] = count;
    }

    count = counts[0];
    delete[] counts;

    return count;
}

// ====================测试代码====================
void Test(const string& testName, int number, int expected)
{
    if(GetTranslationCount(number) == expected)
        cout << testName << " passed." << endl;
    else
        cout << testName << " FAILED." << endl;
}

void Test1()
{
    int number = 0;
    int expected = 1;
    Test("Test1", number, expected);
}

void Test2()
{
    int number = 10;
    int expected = 2;
    Test("Test2", number, expected);
}

void Test3()
{
    int number = 125;
    int expected = 3;
    Test("Test3", number, expected);
}

void Test4()
{
    int number = 126;
    int expected = 2;
    Test("Test4", number, expected);
}

void Test5()
{
    int number = 426;
    int expected = 1;
    Test("Test5", number, expected);
}

void Test6()
{
    int number = 100;
    int expected = 2;
    Test("Test6", number, expected);
}

void Test7()
{
    int number = 101;
    int expected = 2;
    Test("Test7", number, expected);
}

void Test8()
{
    int number = 12258;
    int expected = 5;
    Test("Test8", number, expected);
}

void Test9()
{
    int number = -100;
    int expected = 0;
    Test("Test9", number, expected);
}

int main(int argc, char* argv[])
{
    Test1();
    Test2();
    Test3();
    Test4();
    Test5();
    Test6();
    Test7();
    Test8();
    Test9();

    return 0;
}

7. 礼物的最大价值

/*******************************************************************
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——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================

// 面试题47:礼物的最大价值
// 题目:在一个m×n的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值
// (价值大于0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向左或
// 者向下移动一格直到到达棋盘的右下角。给定一个棋盘及其上面的礼物,请计
// 算你最多能拿到多少价值的礼物?

#include <algorithm>
#include <iostream>

int getMaxValue_solution1(const int* values, int rows, int cols)
{
    if(values == nullptr || rows <= 0 || cols <= 0)
        return 0;

    int** maxValues = new int*[rows];
    for(int i = 0; i < rows; ++i)
        maxValues[i] = new int[cols];

    for(int i = 0; i < rows; ++i)
    {
        for(int j = 0; j < cols; ++j)
        {
            int left = 0;
            int up = 0;

            if(i > 0)
                up = maxValues[i - 1][j];

            if(j > 0)
                left = maxValues[i][j - 1];

            maxValues[i][j] = std::max(left, up) + values[i * cols + j];
        }
    }

    int maxValue = maxValues[rows - 1][cols - 1];

    for(int i = 0; i < rows; ++i)
        delete[] maxValues[i];
    delete[] maxValues;

    return maxValue;
}

int getMaxValue_solution2(const int* values, int rows, int cols)
{
    if(values == nullptr || rows <= 0 || cols <= 0)
        return 0;

    int* maxValues = new int[cols];
    for(int i = 0; i < rows; ++i)
    {
        for(int j = 0; j < cols; ++j)
        {
            int left = 0;
            int up = 0;

            if(i > 0)
                up = maxValues[j];

            if(j > 0)
                left = maxValues[j - 1];

            maxValues[j] = std::max(left, up) + values[i * cols + j];
        }
    }

    int maxValue = maxValues[cols - 1];

    delete[] maxValues;

    return maxValue;
}

// ====================测试代码====================
void test(const char* testName, const int* values, int rows, int cols, int expected)
{
    if(getMaxValue_solution1(values, rows, cols) == expected)
        std::cout << testName << ": solution1 passed." << std::endl;
    else
        std::cout << testName << ": solution1 FAILED." << std::endl;

    if(getMaxValue_solution2(values, rows, cols) == expected)
        std::cout << testName << ": solution2 passed." << std::endl;
    else
        std::cout << testName << ": solution2 FAILED." << std::endl;
}

void test1()
{
    // 三行三列
    int values[][3] = {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };
    int expected = 29;
    test("test1", (const int*) values, 3, 3, expected);
}

void test2()
{
    //四行四列
    int values[][4] = {
        { 1, 10, 3, 8 },
        { 12, 2, 9, 6 },
        { 5, 7, 4, 11 },
        { 3, 7, 16, 5 }
    };
    int expected = 53;
    test("test2", (const int*) values, 4, 4, expected);
}

void test3()
{
    // 一行四列
    int values[][4] = {
        { 1, 10, 3, 8 }
    };
    int expected = 22;
    test("test3", (const int*) values, 1, 4, expected);
}

void test4()
{
    int values[4][1] = {
        { 1 },
        { 12 },
        { 5 },
        { 3 }
    };
    int expected = 21;
    test("test4", (const int*) values, 4, 1, expected);
}

void test5()
{
    // 一行一列
    int values[][1] = {
        { 3 }
    };
    int expected = 3;
    test("test5", (const int*) values, 1, 1, expected);
}

void test6()
{
    // 空指针
    int expected = 0;
    test("test6", nullptr, 0, 0, expected);
}

int main(int argc, char* argv[])
{
    test1();
    test2();
    test3();
    test4();
    test5();

    return 0;
}

8. 最长不含重复字符的子字符串

/*******************************************************************
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——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================

// 面试题48:最长不含重复字符的子字符串
// 题目:请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子
// 字符串的长度。假设字符串中只包含从'a'到'z'的字符。

#include <string>
#include <iostream>

// 方法一:蛮力法
bool hasDuplication(const std::string& str, int position[]);

int longestSubstringWithoutDuplication_1(const std::string& str)
{
    int longest = 0;
    int* position = new int[26];
    for(int start = 0; start < str.length(); ++start)
    {
        for(int end = start; end < str.length(); ++end)
        {
            int count = end - start + 1;
            const std::string& substring = str.substr(start, count);
            if(!hasDuplication(substring, position))
            {
                if(count > longest)
                    longest = count;
            }
            else
                break;

        }
    }

    delete[] position;
    return longest;
}

bool hasDuplication(const std::string& str, int position[])
{
    for(int i = 0; i < 26; ++i)
        position[i] = -1;

    for(int i = 0; i < str.length(); ++i)
    {
        int indexInPosition = str[i] - 'a';
        if(position[indexInPosition] >= 0)
            return true;

        position[indexInPosition] = indexInPosition;
    }

    return false;
}

// 方法一:动态规划
int longestSubstringWithoutDuplication_2(const std::string& str)
{
    int curLength = 0;
    int maxLength = 0;

    int* position = new int[26];
    for(int i = 0; i < 26; ++i)
        position[i] = -1;

    for(int i = 0; i < str.length(); ++i)
    {
        int prevIndex = position[str[i] - 'a'];
        if(prevIndex < 0 || i - prevIndex > curLength)
            ++curLength;
        else
        {
            if(curLength > maxLength)
                maxLength = curLength;

            curLength = i - prevIndex;
        }
        position[str[i] - 'a'] = i;
    }

    if(curLength > maxLength)
        maxLength = curLength;

    delete[] position;
    return maxLength;
}

// ====================测试代码====================
void testSolution1(const std::string& input, int expected)
{
    int output = longestSubstringWithoutDuplication_1(input);
    if(output == expected)
        std::cout << "Solution 1 passed, with input: " << input << std::endl;
    else
        std::cout << "Solution 1 FAILED, with input: " << input << std::endl;
}

void testSolution2(const std::string& input, int expected)
{
    int output = longestSubstringWithoutDuplication_2(input);
    if(output == expected)
        std::cout << "Solution 2 passed, with input: " << input << std::endl;
    else
        std::cout << "Solution 2 FAILED, with input: " << input << std::endl;
}

void test(const std::string& input, int expected)
{
    testSolution1(input, expected);
    testSolution2(input, expected);
}

void test1()
{
    const std::string input = "abcacfrar";
    int expected = 4;
    test(input, expected);
}

void test2()
{
    const std::string input = "acfrarabc";
    int expected = 4;
    test(input, expected);
}

void test3()
{
    const std::string input = "arabcacfr";
    int expected = 4;
    test(input, expected);
}

void test4()
{
    const std::string input = "aaaa";
    int expected = 1;
    test(input, expected);
}

void test5()
{
    const std::string input = "abcdefg";
    int expected = 7;
    test(input, expected);
}

void test6()
{
    const std::string input = "aaabbbccc";
    int expected = 2;
    test(input, expected);
}

void test7()
{
    const std::string input = "abcdcba";
    int expected = 4;
    test(input, expected);
}

void test8()
{
    const std::string input = "abcdaef";
    int expected = 6;
    test(input, expected);
}

void test9()
{
    const std::string input = "a";
    int expected = 1;
    test(input, expected);
}

void test10()
{
    const std::string input = "";
    int expected = 0;
    test(input, expected);
}

int main(int argc, char* argv[])
{
    test1();
    test2();
    test3();
    test4();
    test5();
    test6();
    test7();
    test8();
    test9();
    test10();

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值