Condivisione della tecnologia

Linguaggio C |. Leecode Soluzione al problema del linguaggio C n. 229 Maggior parte degli elementi II

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

argomento:

risposta:

  1. /**
  2. * Note: The returned array must be malloced, assume caller calls free().
  3. */
  4. /*
  5. 假定 num1,num2 为出现次数大于 nums.length / 3 的两个数。(最多出现两个)
  6. 遍历 nums, 若出现 num1、num2 中任意一数,计数+1,若都不等,则计数-1.
  7. 若 num1、num2 有一个计数 < 0,则替换成当前遍历数(更换新的众数)
  8. 数组可能出现 无众数 或只有 一众数 情况,所以需要再次遍历数组,统计所选众数出现次数,将满足条件(出现次数大于 nums.length / 3 )的数加入返回集合。
  9. */
  10. int* majorityElement(int* nums, int numsSize, int* returnSize){
  11. int *arr = NULL;
  12. int can1, can2;
  13. int cnt1 = 0, cnt2 = 0;
  14. int i;
  15. if (nums == NULL || numsSize <= 1) {
  16. *returnSize = numsSize;
  17. return nums;
  18. }
  19. can1 = nums[0];
  20. can2 = nums[1];
  21. for (i = 0; i < numsSize; i++) {
  22. if (nums[i] == can1) {
  23. cnt1++;
  24. continue;
  25. } else if (nums[i] == can2) {
  26. cnt2++;
  27. continue;
  28. } else {
  29. cnt1--;
  30. cnt2--;
  31. }
  32. /* 保证每次只替换一个数据 */
  33. if (cnt1 < 0) {
  34. can1 = nums[i];
  35. cnt1 = 1;
  36. cnt2++;
  37. }
  38. if (cnt2 < 0) {
  39. can2 = nums[i];
  40. cnt2 = 1;
  41. cnt1++;
  42. }
  43. }
  44. cnt1 = 0;
  45. cnt2 = 0;
  46. for (i = 0; i < numsSize; i++) {
  47. if (nums[i] == can1) {
  48. cnt1++;
  49. } else if (nums[i] == can2) {
  50. cnt2++;
  51. }
  52. }
  53. arr = (int *)malloc(sizeof(int) * 2);
  54. *returnSize = 0;
  55. i = 0;
  56. if (cnt1 > numsSize / 3) {
  57. arr[i++] = can1;
  58. *returnSize += 1;
  59. }
  60. if (cnt2 > numsSize / 3) {
  61. arr[i++] = can2;
  62. *returnSize += 1;
  63. }
  64. return arr;
  65. }