算法第五週——貪心算法

55. Jump Game

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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.

目標:判斷從數組頭開始,每一元素中的數字爲可跳轉的最大距離,是否可以到達數組結尾。

使用貪心算法,遍歷數組的同時不斷更新可以達到的最遠距離,若能超過數組的大小則返回正確,否則返回錯誤。

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int move=0;
        for(int i=0;i<nums.size()&&i<=move;i++)
            move=max(move,i+nums[i]);
        return move>=nums.size()-1;
    }
};

45. Jump Game II

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.)

目標:在上一題的基礎上找到跳轉的最小次數。

找到當前節點所能跳轉的最遠節點,遍歷當前節點到該節點,刷新最遠跳轉距離。沒重複一次記爲跳轉次數加一。

class Solution {
public:
    int jump(vector<int>& nums) {
        int Size= nums.size()-1;
        int steps = 0, start = 0, end = 0;
        while (end < Size) {
            steps++; 
            int maxend = end + 1;
            for (int i = start; i <= end; i++) {
                if (i + nums[i] >= Size) 
                    return steps;
                maxend = max(maxend, i + nums[i]);
            }
            start = end + 1;
            end = maxend;
        }
        return steps;
    }
};

134. Gas Station

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

目標:在有N個加油站的環形路線上,第i個加油站所有的汽油爲gas[i],汽車從i開到i+1需要cost[i]汽油。判斷從任意加油站開始能否遍歷整條路線。

遍歷整個路線,start=0,記錄起始位置,tank記錄當前油箱汽油儲量,若出現<0則將此位置置爲start,tank清零。total爲最終汽油儲量,若小於零則返回-1.

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int start=0,total=0,tank=0;
        for(int i=0;i<gas.size();i++)
        {
            tank+=gas[i]-cost[i];
            if(tank<0)
            {
                start=i+1;
                total+=tank;
                tank=0;
            }
        }
        total+=tank;
        return total>=0?start:-1;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章