小代码、小算法

来源:互联网 发布:淘宝网店标志可以改吗 编辑:程序博客网 时间:2024/04/23 23:51

小代码、小算法

第一个

question

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)


知识标签:array, greedy, algorithm

code

class Solution {public:    int jump(vector<int>& nums)     {        int step = 0;// 走过的步数        int curRange = 0;// 当前要走的距离        int curMaxRange = 0;// 当前能走的最大距离        for(int i = 0; i != nums.size(); ++i)        {            // 如果走投无路            if(curMaxRange < i)                return -1;            // 如果当前要走的距离小于当前距离的话,向前走一大步            if(curRange < i)            {                ++step;                curRange = curMaxRange;            }            //比较并记录当前能走的最大距离            curMaxRange = curMaxRange > nums[i] + i ? curMaxRange : nums[i] + i;        }        //返回的结果就是到达目标最小的步数        return step;    }};

第二个

question

一个整数元素的一维数组,例如:-2, 5, 3, -3, 4, -8, 6,
这个数字当然有很多子数组,那么问众多子数组中,子数组各元素之和最大值是多少呢?


知识标签:array, algorithm

code

#include<iostream>int getMaxSum(int a[], int length){    //当前子数组和    int sum = 0;    //当前子数组最大和    int MaxSum = 0;    //遍历    for(int i = 0; i != length; ++i)    {        sum += a[i];        //如果sum为负,置0        if(sum < 0)            sum = 0;        //得到当前最大子数组和        MaxSum = sum > MaxSum ? sum : MaxSum;    }    return MaxSum;}int main(void){    int a[] = {-2, 5, 3, -3, 4, -8, 6};    std::cout << getMaxSum(a, sizeof(a)/sizeof(int)) << std::endl;    return 0;}

第三个

question

判断大小端
大小端说明:
对于int型数据:0x12345678,内存中的存储方式为:
–低地址位—高低址位—->
大端: 12 34 56 78
小端: 78 56 34 12

code

#include<iostream>int main(void){    short int a = 0x1234;    if(static_cast<char>(a) == 0x34)        std::cout << "小端" << std::endl;    else        std::cout << "大端" << std::endl;    return 0;}

第四个

question

写一个函数,完成内存之间的拷贝

code

#include<iostream>void* mymemcpy(void* dest, const void* src, size_t count){    char* pdest = static_cast<char*>(dest);    const char* psrc = static_cast<const char*>(src);    size_t i;    if(pdest > psrc && pdest < psrc + count)        for(i = count - 1; i != -1; --i)            pdest[i] = psrc[i];    else        for(size_t i = 0; i < count; ++i)            pdest[i] = psrc[i];    return dest;}int main(void){    char str[] = "0123456789";    mymemcpy(str + 1, str, 9);    std::cout << str << std::endl;    return 0;}

结果

0012345678

0 0