作者devilkool (可可粉)
標題Re: [閒聊] 每日leetcode
時間2024-11-07 01:59:40
3011. Find if Array Can Be Sorted
偷看hint才會寫,假如相鄰兩數字二進位的1的數量不一樣
前面又比後面大的話就是false,1的數量一樣的話就找出這一組最大的值跟下一組做比較
public bool CanSortArray(int[] nums)
{
if (nums.Length == 1)
{
return true;
}
var currentSetbitsCount = Convert.ToString(nums[0],2).Count(c => c ==
'1');
var currentMax = nums[0];
var currentMin = nums[0];
var lastMax = int.MinValue;
for (int i=1;i<nums.Length;i++)
{
var setbitsCount = Convert.ToString(nums[i],2).Count(c => c ==
'1');
if (setbitsCount != currentSetbitsCount)
{
if (lastMax > currentMin)
{
return false;
}
lastMax = currentMax;
currentMin = nums[i];
currentMax = nums[i];
currentSetbitsCount = setbitsCount;
}
else
{
currentMax = Math.Max(nums[i], currentMax);
currentMin = Math.Min(nums[i], currentMin);
}
}
return currentMin > lastMax;
}
--
※ 發信站: 批踢踢實業坊(ptt-club.com.tw), 來自: 36.230.32.220 (臺灣)
※ 文章網址: https://ptt-club.com.tw/Marginalman/M.1730915983.A.84D