力扣Leetcode 面试题56 - I. 数组中数字出现的次数
2021-02-04 10:18
阅读:629
标签:int 位运算 空间 clu 判断 temp tco code space
面试题56 - I. 数组中数字出现的次数
一个整型数组 nums
里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
示例 1:
输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]
示例 2:
输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10] 或 [10,2]
限制:
2
题解思路
我的思路是排序之后逐个判断,符合条件的直接覆盖当前数组的头两个,因为要符合题目条件给的空间复杂度,不能另开,而且题目说只有俩,可以直接判断满足两个后返回,满足时间复杂度。
#include
using namespace std;
int main()
{
vector nums{1, 2, 10, 4, 1, 4, 3, 3};
sort(nums.begin(), nums.end());
int l = 0, temp;
for (int i = 0; i
问题是力扣的oj实在整不明白 报奇奇怪怪的错 直接跑上面的是符合的
下面是官方题解
异或
异或的代码短是短 更不好理解倒是 还涉及了位运算
class Solution {
public:
vector singleNumbers(vector& nums) {
int ret = 0;
for (int n : nums)
ret ^= n;
int div = 1;
while ((div & ret) == 0)
div {a, b};
}
};
排序
这个和我的排序思路差不多
//排序后的数组内,相同的元素是相邻的
class Solution {
public int[] singleNumbers(int[] nums) {
Arrays.sort(nums);
int len = nums.length;
int[] res = new int[2];
Arrays.fill(res, Integer.MAX_VALUE);
boolean found_first = false;
for (int i = 0; i + 1
力扣Leetcode 面试题56 - I. 数组中数字出现的次数
标签:int 位运算 空间 clu 判断 temp tco code space
原文地址:https://www.cnblogs.com/coderzjz/p/12795102.html
文章来自:搜素材网的编程语言模块,转载请注明文章出处。
文章标题:力扣Leetcode 面试题56 - I. 数组中数字出现的次数
文章链接:http://soscw.com/index.php/essay/50858.html
文章标题:力扣Leetcode 面试题56 - I. 数组中数字出现的次数
文章链接:http://soscw.com/index.php/essay/50858.html
评论
亲,登录后才可以留言!