Re: [閒聊] 每日leetcode

作者: JIWP (JIWP)   2024-11-08 22:44:18
2275. Largest Combination With Bitwise AND Greater Than Zero
有一個正整數矩陣:candidates
對candidates裡每種組合進行 & 操作
對於每個&操作後大於的組合
請回傳長度最長是多少?
思路:
將每個candidate內部的數字轉換成二進位
接著統計每一位元有幾個1
回傳最多1的數量就好
C code :
int largestCombination(int* candidates, int candidatesSize) {
int *record = (int*)calloc(25, sizeof(int)), maxnum = 0;
for (int i = 0; i < candidatesSize; i++) {
if (candidates[i] > maxnum) {
maxnum = candidates[i];
}
}
int idx = 0;
for (int i = 1; i <= maxnum; i <<= 1) {
for (int j = 0; j < candidatesSize; j++) {
if ((candidates[j] & i) >0) {
record[idx]++;
}
}
idx++;
}
int ans = 0;
for (int i = 0; i < 25; i++) {
if (record[i] > ans) {
ans = record[i];
}
}
return ans;
}
作者: sustainer123 (caster)   2024-11-08 22:48:00
又C 你要卷死我了

Links booklink

Contact Us: admin [ a t ] ucptt.com