leetcode 2442.反转之后不同整数的数目

1.题目要求:

c 复制代码
给你一个由 正 整数组成的数组 nums 。

你必须取出数组中的每个整数,反转其中每个数位,并将反转后得到的数字添加到数组的末尾。这一操作只针对 nums 中原有的整数执行。

返回结果数组中 不同 整数的数目。

 

示例 1:

输入:nums = [1,13,10,12,31]
输出:6
解释:反转每个数字后,结果数组是 [1,13,10,12,31,1,31,1,21,13] 。
反转后得到的数字添加到数组的末尾并按斜体加粗表示。注意对于整数 10 ,反转之后会变成 01 ,即 1 。
数组中不同整数的数目为 6(数字 1、10、12、13、21 和 31)。
示例 2:

输入:nums = [2,2,2]
输出:1
解释:反转每个数字后,结果数组是 [2,2,2,2,2,2] 。
数组中不同整数的数目为 1(数字 2)。
 

提示:

1 <= nums.length <= 105
1 <= nums[i] <= 106
c 复制代码
//把数字反转的函数
int reverse(int n){
    int number = n;
    int count = 0;//
    while(number){
        count++; 
        number /= 10;
    }
    number = n;
    int sum = 0;
    while(number){
        int temp = number % 10;
        sum +=  (temp * pow(10,count - 1));
        count--;
        number /= 10;
    }
    return sum;
}
int countDistinctIntegers(int* nums, int numsSize) {
    int* number = (int*)malloc(sizeof(int) * numsSize * 2);//设立二倍长度数组,用来存放数组
    memcpy(number,nums,sizeof(int) * numsSize);
    int j = 0;
    j = numsSize;
    //开始进行数字反转
    for(int i = 0;i < numsSize;i++){
        int ret = reverse(nums[i]);
        number[j] = ret;
        j++;
    }
    //用哈希函数来判断不同的整数数目
    int* temp = (int*)malloc(sizeof(int) * 1000000);
    memset(temp,0,sizeof(int) * 1000000);
    for(int i = 0;i < numsSize * 2;i++){
        int index = number[i] - 1;
        temp[index] = number[i];
    }
    int count = 0;
    for(int i = 0;i < 1000000;i++){
        if(temp[i] != 0){
            count++;
        }
    }
    return count;
}

大家如果觉得好的话,不妨给个免费的赞吧,谢谢了

相关推荐
ChillJavaGuy14 小时前
常见限流算法详解与对比
java·算法·限流算法
散11214 小时前
01数据结构-01背包问题
数据结构
sali-tec14 小时前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
消失的旧时光-194314 小时前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww14 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
你怎么知道我是队长15 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒15 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
苏小瀚16 小时前
[数据结构] 排序
数据结构
纪元A梦17 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_17 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表