算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !今天和大家聊的問題叫做 消除游戲,我們先來看題面:https://leetcode-cn.com/problems/elimination-game/You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.Keep repeating the steps again, alternating left to right and right to left, until a single number remains.Given the integer n, return the last number that remains in arr.首先,從左到右,從第一個數(shù)字開始,每隔一個數(shù)字進行刪除,直到列表的末尾。第二步,在剩下的數(shù)字中,從右到左,從倒數(shù)第一個數(shù)字開始,每隔一個數(shù)字進行刪除,直到列表開頭。我們不斷重復(fù)這兩步,從左到右和從右到左交替進行,直到只剩下一個數(shù)字。返回長度為 n 的列表中,最后剩下的數(shù)字。示例
輸入:
n = 9,
1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6
輸出:
6
解題
class Solution {
public:
int lastRemaining(int n) {
if(n == 1)
return 1;
return 2*(n/2)+2 - 2*lastRemaining(n/2);
}
};
好了,今天的文章就到這里,如果覺得有所收獲,請順手點個在看或者轉(zhuǎn)發(fā)吧,你們的支持是我最大的動力 。