博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Find the element that appears once
阅读量:4150 次
发布时间:2019-05-25

本文共 1287 字,大约阅读时间需要 4 分钟。

reference: 

Problem Definition:

Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once. Expected time complexity is O(n) and O(1) extra space.

Examples:

Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3}Output: 2

Solution:

We can sum the bits in same positions for all the numbers and take modulo with 3. The bits for which sum is not multiple of 3, are the bits of number with single occurrence.

Let us consider the example array {5, 5, 5, 8}. The 101, 101, 101, 1000

Sum of first bits%3 = (1 + 1 + 1 + 0)%3 = 0;

Sum of second bits%3 = (0 + 0 + 0 + 0)%0 = 0;

Sum of third bits%3 = (1 + 1 + 1 + 0)%3 = 0;

Sum of fourth bits%3 = (1)%3 = 1;

Hence number which appears once is 1000

Code:

int getSingle(int arr[], int n){    // Initialize result    int result = 0;     int x, sum;     // Iterate through every bit    for (int i = 0; i < INT_SIZE; i++)    {      // Find sum of set bits at ith position in all      // array elements      sum = 0;      x = (1 << i);      for (int j=0; j< n; j++ )      {          if (arr[j] & x)            sum++;      }       // The bits with sum not multiple of 3, are the      // bits of element with single occurrence.      if (sum % 3)        result |= x;    }     return result;}

转载地址:http://urxti.baihongyu.com/

你可能感兴趣的文章
Simple Guide to use the gdb tool in Android environment
查看>>
Netconsole to capture the log
查看>>
Build GingerBread on 32 bit machine.
查看>>
How to make SD Card world wide writable
查看>>
Detecting Memory Leaks in Kernel
查看>>
Linux initial RAM disk (initrd) overview
查看>>
Timestamping Linux kernel printk output in dmesg for fun and profit
查看>>
There's Much More than Intel/AMD Inside
查看>>
CentOS7 安装MySQL 5.6.43
查看>>
使用Java 导入/导出 Excel ----Jakarta POI
查看>>
本地tomcat 服务器内存不足
查看>>
IntelliJ IDAE 2018.2 汉化
查看>>
基于S5PV210的uboot移植中遇到的若干问题记录(一)DM9000网卡移植
查看>>
Openwrt源码下载与编译
查看>>
我和ip_conntrack不得不说的一些事
查看>>
Linux 查看端口使用情况
查看>>
文件隐藏
查看>>
两个linux内核rootkit--之二:adore-ng
查看>>
两个linux内核rootkit--之一:enyelkm
查看>>
关于linux栈的一个深层次的问题
查看>>