整数数组中找出只出现了一次的数

本文提供了两种情况下查找数组中唯一不重复元素的方法:一种是在所有元素都出现三次的情况下找到仅出现一次的元素;另一种是在所有元素都出现两次的情况下找到仅出现一次的元素。通过位操作实现了高效解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers, every element appears three times except for one. Find that single one.

public class Solution {
    public int singleNumber(int[] A) {
        int ones=0,twos=0,threes=0;
        for(int i=0;i<A.length;i++){
            twos|=ones&A[i];
            ones^=A[i];
            threes=ones&twos;
            ones&=~threes;
            twos&=~threes;
        }
        return ones!=0?ones:twos;
    }
}

Given an array of integers, every element appears twice except for one. Find that single one.

public class Solution {
    public int singleNumber(int[] A) {
        int ones=0;
        for(int i=0;i<A.length;i++){
            ones^=A[i];
        }
        return ones;
    }
}
### 找到两个整数数组的共同元素 要找到两个整数数组中的共同元素,可以通过以下方法实现。以下是基于 C 语言的一种解决方案: #### 方法描述 为了高效地解决问题,可以采用哈希表或者排序加双指针的方式。 1. **使用哈希表** 创建一个辅助据结构(如布尔数组或集合),记录第一个数组中出现过的元素。遍历第二个数组时,检查这些元素是否存在于该辅助据结构中。如果存在,则将其加入结果集中,确保每个元素只被添加一次[^1]。 2. **排序加双指针法** 将两个数组分别排序后,利用双指针技术逐一比较两者中的元素。当遇到相等的情况时,说明找到了公共元素;如果不等,则移动值较小一方对应的指针继续查找。这种方法的时间复杂度主要取决于排序操作 \(O(n \log n)\)[^4]。 下面是具体的代码实现: ```c #include <stdio.h> #include <stdlib.h> // 函声明 void findCommonElements(int *arr1, int size1, int *arr2, int size2); int main() { // 输入处理部分 int N1, N2; scanf("%d", &N1); int array1[N1]; for (int i = 0; i < N1; ++i) { scanf("%d", &array1[i]); } scanf("%d", &N2); int array2[N2]; for (int j = 0; j < N2; ++j) { scanf("%d", &array2[j]); } // 调用函打印交集 findCommonElements(array1, N1, array2, N2); return 0; } void findCommonElements(int *arr1, int size1, int *arr2, int size2) { // 对两个数组进行快速排序 qsort(arr1, size1, sizeof(int), compare); qsort(arr2, size2, sizeof(int), compare); int index1 = 0, index2 = 0; while (index1 < size1 && index2 < size2) { if (arr1[index1] == arr2[index2]) { printf("%d ", arr1[index1]); do { index1++; } while(index1 < size1 && arr1[index1]==arr1[index1-1]); // 去重逻辑 do { index2++; } while(index2 < size2 && arr2[index2]==arr2[index2-1]); // 去重逻辑 } else if (arr1[index1] < arr2[index2]) index1++; else index2++; } } // 辅助比较函用于qsort() int compare(const void* a, const void* b){ return (*(int*)a - *(int*)b); } ``` 上述程序实现了读取输入、排序以及通过双指针寻找共同元素的功能[^2]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值