第一章:位运算-------出现k次与出现1次

算法 | 如何用位运算从一堆数中寻找出现K次的数? 本文主要介绍如何使用位运算从一堆数中寻找出现K次的数,这一堆数中有很多数出现了M次,只有一个数出现了K次,并且K是小于M的,另外要求额外空间复杂度为O(1),时间复杂度为O(n),那么该如何寻找出这个数呢?例如,给出一个数组,K = 2,M = 3。在这个数组中,只有1这个元素出现了2次,其他的元素都出现了3次,现在要求使用位运算把1这个元素找出来。本文主要介绍如何使用位运算从一堆数中寻找出现K次的数,利用了二进制、或运算、以及题目中M次的逻辑关系。如果你有更好的办法,欢迎在评论区留言交流。 阅读详情

第一章:位运算-------出现k次与出现1次

 

问题:

数组中只有一个数出现了一次,其他的数都出现了k次,请输出只出现1次的数。

 

知识点:

2个相同的2进制数,做不进位加法,结果为0;

10个相同的10进制数,做不进位加法,结果为0;

k个相同的k进制数,做不进位加法,结果为0;

 

思路:

将这些数,全部转换为k进制数,然后做不进位加,最后将结果转换为十进制数。

 

#include<iostream>
#include<algorithm>
//#include<cmath>
using namespace std;

//十进制数转K进制 
string decTok(int dec,int k){
	string ret="";  //作为结果
	
	while(dec>0){
		ret+=char(dec%k+'0');     //如:5+'0'='5' 
		dec/=k;
	} 
	reverse(ret.begin(),ret.end());
	return ret;
}

//K进制转十进制
int kTodec(string str,int k){
	int ans=0;
	for(int i=0;i<str.size();i++){
		ans=ans*k+(str[i]-'0');        //020  首位是最高位 
		//ans+=(str[i]-'0')*pow(k,str.size()-1-i);
	}
	return ans;
} 

int main(){
	int n[]={1,1,1,3,3,3,5,5,5,9,9,9,6,7,7,7};
	int k=3;
	
	string str[16];
	for(int i=0;i<16;i++){
		str[i]=decTok(n[i],k);
	}
	
	//找出16条字符串中最大长度
	int maxlen=0;
	int len;
	for(int i=0;i<16;i++){
		len=str[i].size();
		maxlen=max(maxlen,len);     //不能用: maxlen=max(maxlen,str[i].size())
	} 
	
	//16条字符串中,若字符串长度<maxlen,则进行补齐,以便逐位做不进位加
	for(int i=0;i<16;i++){
		while(str[i].size()<maxlen){
			str[i]="0"+str[i];
		}
	} 
	
	//ans:结果。初始化 
	string ans="";
	while(ans.size()<maxlen){
		ans+="0";
	}
	
	//16条字符串做不进位加
	for(int i=0;i<16;i++){
		for(int j=0;j<maxlen;j++){
			ans[j]=char(((str[i][j]-'0')+(ans[j]-'0'))%k+'0');
		}
	} 
	cout<<ans<<endl;
	
	//ans字符串结果转为10进制数 
	int finalans=kTodec(ans,k);
	cout<<finalans<<endl;
		 
	return 0;
}

结果:

蓝桥杯实战应用【算法代码篇】-出现k次与出现1次(附Java和C++代码) 给定一个长度为 n 的整型数组 arr 和一个整数 k(k>1)。已知 arr 中只有 1 个数出现一次,其他的数都出现 k 次。请返回只出现了 1 次的数。示例1:输入:[5,4,1,1,5,1,5],3返回值:4示例2:输入:[2,2,1],2返回值:1。... 阅读详情

相关推荐

出现k次与出现1次,二进制中有几个1

题目1: 数组中只有一个数出现了一次其他数均出现k次,求出出现一次的数 算法思想与代码写一起了,见注释 public class 出现k次与1次 { /* * 【当k为偶数奇数都适用】 * 算法思想: * 1,把所有的数字转化为k进制 * 2,让转化后的数每一相同的位相加 * 3,每一位相加后的数除k取余得到一个k进制的数 * 4,将该数转化为十进制即可输出 */ public static void main(String[] args) { int [] arr={2,2,2,2,3,3,3,3,6,6,6,6,9,9,9,9,8,8,8,8,7,5,5,5

1070: PIPI的数组

题目描述 PIPI现在有一个全部为正整数组成的数组,他想知道元素 v 第 k次出现在数组中的位置,胖虎能帮帮PIPI吗? PIPI是个好奇心很重的人,他会有m次询问哦~ 输入 输入包含多组测试样例。 对于每一组测试样例,第一行包含两个正整数 n,m .代表数组的长度和询问的次数。 (1<=n,m<=105) 第二行包括n个正整数,每个正整数 v < 106。 接下来包含m组询问,...

weixin_44433678的博客 438

(详细教程)opencv+pycharm+笔记本摄像头 做一个人脸识别

文章目录 前言 一、pandas是什么? 二、使用步骤 1.引入库 2.读入数据 总结 一、安装opencv-python 这里推荐使用pycharm直接安装opencv-python 打开文件——设置——python解释器——点击+号 搜索opencv-python,点击安装包,等待片刻即可安装好 检查是否安装好,新建一个项目输入以下代码,若无报错则安装好 import cv2 二、准备分类器 咱们使用opencv官方提供的分类器,包括面部识别,侧...

qq_52852432的博客 1万+

算法题_位运算_9_出现一次的数字和出现k次的数字

位运算--出现一次的数字和出现k次的数字

Window_mouse的博客 1万+

onnxruntime-gpu版本选择与CUDA环境配置实战指南

本文是onnxruntime-gpu版本选择与CUDA环境配置的实战指南。针对AI模型部署中常见的GPU无法调用问题,核心在于确保onnxruntime-gpu版本与系统CUDA Toolkit版本严格匹配。文章详细讲解了如何精准确定CUDA版本、查找官方对应关系、执行正确安装命令,并通过完整测试脚本验证GPU是否成功启用,最后提供了常见问题排查与生产环境调优建议。

weixin_29164091的博客 537

RT-Thread与LWIP协议栈在GD32F450XX上的移植实战:从FreeRTOS到RT-Thread的切换指南

本文详细介绍了将LWIP协议栈从FreeRTOS移植到RT-Thread系统,并在GD32F450XX开发板上实现的完整实战指南。重点解析了sys_arch适配层、邮箱与信号量接口的关键改造,以及网络驱动ethernetif.c的适配步骤,帮助开发者解决线程通信差异,实现稳定网络连接。

linux6sysadmin的博客 834

#每天一道算法题:出现一次与出现k次的数

出现一次与出现k次的数,分别使用hashMap和不进位加法两种解法,超详细,每句代码都有注释!!!

黑虎阿福的博客 536

Kubernetes(K8s)从入门到精通系列之一:一篇文章了解K8s全部核心知识点

Kubernetes(K8s)从入门到精通系列之一:一篇文章了解K8s全部核心知识点

zhengzaifeidelushang的博客 863

K-th occurrence HDU - 6704 (主席树+后缀数组+二分)

题目传送 题意:给出一个字符串,找出某个子串第k次出现的位置 思路:后缀数组sa[i]数组表示排名第i的后缀第一次出现的下标,求第k次出现的下标只需要在某个区间中求sa数组中的第k大即可(主席树求第k大),确定区间时利用后缀数组中的lcp确定与子串具有相同前缀的后缀第一次出现位置和最后一次出现位置(枚举超时,二分实现)。 代码: #include <iostream> #in...

speaker__的博客 306

【漏洞复现】爱数云盘 Usrm_GetAllUsers 未授权访问漏洞

爱数 AnyShare存在未授权漏洞,未授权的攻击者可以通过该漏洞获取用户名信息。

qq_67810151的博客 3140

通过Robotstudio修改机器人程序的具体方法和步骤

通过Robotstudio修改机器人程序的具体方法和步骤

Robot_PLC_HMI_Automation 6415

面试题38. 数字在排序数组中出现的次数

题目描述 统计一个数字在排序数组中出现的次数。例如输入排序数组[1, 2, 3, 3, 3, 3, 4, 5]和数字3,由于3在这个数组中出现了4次,因此输出4思路1: 很明显,从头遍历数组,就能统计出3出现的次数,时间复杂度为O(n) Java 代码如下:// O(n)的方法 public class Solution { public int GetNumberOfK(int []

两鬓已不能斑白的专栏 546

STM32实战开发(122):基于STM32的溶解氧检测系统设计与实现

溶解氧(DO, Dissolved Oxygen)是水质检测中至关重要的指标之一,尤其是在环境监测、工业废水处理以及水产养殖等领域,溶解氧的浓度直接影响到水体的生态环境和生物的健康。电流的大小就可以用来反映水中溶解氧的浓度。本博客将详细介绍如何基于STM32微控制器开发一个智能溶解氧检测系统,内容涵盖系统的硬件设计、软件开发、优化与调试等方面,提供实际的代码实现与实验数据,并展望溶解氧检测系统在物联网环境下的应用。为了提高系统的精度,可以优化ADC的采样率,增加传感器的校准频率,或使用更加精确的传感器。

2201_76125393的博客 1607

【手把手带你刷LeetCode】——02.出现1次和K次的数(位运算)

【前言】:Hello,铁汁们好,又见面咯。今天是LeetCode打卡第二天,很高兴能和你一起学习,咱们一起加油。 原题:出现1次与出现K次的数 题目描述: 给定一个长度为 n的整型数组 arr和一个整数 k(k>1) 。 已知 arr中只有 1 个数出现一次,其他的数都出现 k次。 请返回只出现了 1 次的数。 示例1: 输入:[5,4,1,1,5,1,5],3 返回值:4 示例2: 输入:[2,2,1],2 返回值:1 哈哈,看过我之前关于位运算博客的童...

安然无虞的博客 4265

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

位运算-出现K次与出现1次

出现K次与出现1次题目描述应会知识实现思路代码实现 题目描述 数组中只有一个数只出现1次,其它数都出现K次,将出现1次的数输出。 应会知识 位运算符:异或**^** 可以将其理解为不进位相加; 例:1+1=0,0+0=0,1+0=1; 10异或12(二进制) 10------1 0 1 0 12------1 1 0 0 结果: 0 1 1 0 只有在其不相等时为1 必须搞懂:用不进位的...

m0_46643508的博客 380

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

1.6 出现k次与出现1次

Chapter1: 位运算的奇技淫巧 6. 出现k次与出现1次 题目 数组中只有一个数只出现了1次,其它的数都出现了k次,请输出只出现了一次的数。 其中k为用户输入 算法 解法1(使用位运算技巧) 使用 hashmap 效果是一样的,代码还更精简,这个稍后数据结构部分再了解 原理 k个k进制数不进位相加 结果是 0 解法 将这个数组中的数全部转为k进制 除k取余法(通用的计...

bloger博客 286

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

出现K次与出现1次

题目如下: public class 出现K次与出现1次 { /** * @param args */ public static void main(String[] args) { // mytest(); // 位运算解法 int a[] = { 2, 2, 2, 9, 7, 7, 7, 3, 3, 3, 4, 4, 4, 5, 5, 5 }; int le...

最白の白菜的博客 248

位运算(8)—— 出现k次与出现1次

题目   数组中只有一个数出现了一次,其他的数都出现了k次,请输出只出现了1次的数。 分析   例如2个二进制数10做不进位加法,结果为二进制00;10个十进制数20做不进位加法,结果为十进制0,由此可得上图规律,k个相同的k进制数做不进位加法,结果为0。故我们可以将所有的数转化成为K进制,然后做K进制的不进位加法,得出的结果再从K进制转换为10进制。 代码实现 public class _07出现k次与出现1次 { public static void main(String[] args) {

小R.的博客 407

1.8 编程实践:出现k次与出现1次(两种解法)

Problem: 数组中只有一个数出现了1次,其他的数都出现了k次,请输出出现了1次的数。 其中k你输入的 解法1 : 使用HashMap来解决问题,这里不多讲 实现代码:  /** * 解法2-使用HashMap(更容易想到) * @param nums * @return */ public static int getOnce2(int[] nums) { M...

the blog of Lee 1057

Java算法--第一章--位运算符(8)出现k次与出现1次

Java算法–第一章–位运算符(8)出现k次与出现1次 题目:数组中只有一个数出现了1次,其他的数都出现了k次,请输出只出现了1次的数。 补充知识点:(1)2个相同的二进制数做不进位加法,结果为零; (2)10个相同的十进制数做不进位加法,结果位零; (3)k个相同的k进制数做不进制加法,结果为零 代码: package exer1; public class 出现k次和出现1次 { public static void main(String[] args) { int[] ar

wp_886的博客 337

位运算——出现K次的数

在arr中,只有一种数出现了K次,其他数都出现了M次 找出那个出现了K次的数

Go的全部 555

位运算 出现K次与出现1次(C++代码)

出现K次与出现1次 这题难度上升,涉及其他基础知识。建议:多看几遍思路和代码,自己动手模拟下。 解题思路: 解题的突破口:利用k个K进制的数进行不进位加法,结果是 0 的结论 先把十进制的数转为k进制,并采用字符串倒序存储 用除k取余法(通用的计算方法),将数组中的数转为k进制数。 因为转化为k进制后要按位(列)进行计算,采用字符串的形式储存。转化为k进制后由于数的大小不同,长度也有可能不同,虽然对于有k个数的数字而言求和都是0没区别,但对要求的那个数来说位序很关键,(计算时是字符串是由左到右计算,而

Dragon_1718的博客 500

出现k次与出现1次

解法1; HashMap public static int getOnce2(int[] nums) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if(map.containsKey(nums[i])) { int num = map.get(nums[i]); num++; map.pu.

m0_43425029的博客 166

位运算全面总结,关于位运算看这篇就够了

关于位运算的奇技淫巧,看完这篇你就能灵活使用位运算了。

pursuit的博客 13万+
上一篇: 第一章:位运算-------输入浮点数,输出对应二进制数
下一篇: 第二章 :查找与排序---------递归、查找与排序补充
Estrellas_
博客等级 码龄9年 273粉丝 233原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址