*Find the Number Occurring Odd Number of Times
2016-01-24 05:44
453 查看
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.
Example:
I/P = [1, 2, 3, 2, 3, 1, 3]
O/P = 3
A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and inner loop counts number of occurrences of the element picked by outer loop. Time complexity of this solution is O(n2).
A Better Solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O(n). But it requires extra space for hashing.
The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring element. Please note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x.
Below are implementations of this best approach.
Program:
Example:
I/P = [1, 2, 3, 2, 3, 1, 3]
O/P = 3
A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and inner loop counts number of occurrences of the element picked by outer loop. Time complexity of this solution is O(n2).
A Better Solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O(n). But it requires extra space for hashing.
The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring element. Please note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x.
Below are implementations of this best approach.
Program:
//in c++ #include <stdio.h> int getOddOccurrence(int ar[], int ar_size) { int i; int res = 0; for (i=0; i < ar_size; i++) res = res ^ ar[i]; return res; } /* Diver function to test above function */ int main() { int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; int n = sizeof(ar)/sizeof(ar[0]); printf("%d", getOddOccurrence(ar, n)); return 0; }
相关文章推荐
- Leetcode 189. Rotate Array
- Union and Intersection
- Leetcode 74. Search a 2D Matrix
- Leetcode 81. Search in Rotated Sorted Array II
- 2016感怀
- Leetcode 33. Search in Rotated Sorted Array
- 小娜学法(14): 立善法于天下,则天下治
- mac OS X Yosemite (10.10.5) 下 安装vim 7.4笔记
- Leetcode -229. Majority Element
- LRU Cache
- mysql外键约束
- java解析xml文件(三种方式-(dom ,jdom ,dom4j)
- java模拟并发请求
- Java连接各种数据库
- java中IO流的学习笔记(3、转换流的写入和读取)
- MVP
- Class-dump安装和简单使用
- PHP 系统变量 环境变量
- php mysql数据库操作mysql和pdo的实现
- linux中系统性能检测工具pidstat学习