You are given a 0-indexed integer array nums whose length is a power of 2.
Apply the following algorithm on nums:
Let n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2.
For every even index i where 0 <= i < n / 2, assign the value of newNums[i] as min(nums[2 * i], nums[2 * i + 1]).
For every odd index i where 0 <= i < n / 2, assign the value of newNums[i] as max(nums[2 * i], nums[2 * i + 1]).
Replace the array nums with newNums.
Repeat the entire process starting from step 1.
Return the last number that remains in nums after applying the algorithm.
題感有點長,大意是將一個陣列在迭代時長度減半,新陣列的奇數(odd),是舊陣列的 max(nums[2 * i], nums[2 * i + 1])
,偶數(even)則是舊陣列的min(nums[2 * i], nums[2 * i + 1])
,使用遞迴求解
var minMaxGame = function(nums) {
function lastRemaining(n){
if(n.length===1){
return n[0];
}
const newArray=[];
for(let i=0;i<n.length/2;++i){
if(i%2===0){
newArray.push(Math.min(n[2 * i], n[2 * i + 1]));
}else{
newArray.push(Math.max(n[2 * i], n[2 * i + 1]));
}
}
return lastRemaining(newArray);
}
return lastRemaining(nums);
};