小代碼、小算法

小代碼、小算法

第一個

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

發佈了26 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章