Question 15th: separate numbers
Given an array, except for a number that appears once, the remaining number appears three times. Find the number of occurrences.
For example: {1, 2, 1, 2, 1, 2, 7}, find 7.
Format:
Input N in the first line indicates the length of the array, and input a [n] In the next line (the input array must meet the problem description requirements ), the number of output records that appear only once.
Requirements:
Your algorithm can only be a linear time complexity and cannot use extra space ~
Sample Input
40 0 0 5
Sample output
5
Problem Analysis:
In fact, this question is not difficult (although "extra space is not available"). The main principle is to traverse the number already exists in the array. The principle of judging whether there are duplicates is to set a counter, for more information, see the code and comments.
#include <stdio.h>int main(){int i,j,n,A[10000],count = 0;//count为计数器 scanf("%d",&n);//为n赋值 for(i = 0;i < n;i++)//为数组赋值 scanf("%d",&A[i]);for(i = 0;i < n;i++)//第一层循环:读取每个数,与后面数值作比较 {for(j = 0;j < n;j++)//第二次循环:读取i后面的数 {if(A[i] == A[j])//判断外层数是否与内层数相等 count++;//若相等则将+1 }if(count == 1)//若计数器==1(也就是数组中只有其本身) {printf("%d\n",A[i]);//输出此数并结束 return 0;}count = 0;}return 0;}
If you cannot understand it, please leave a message or leave an email !!! O (partition _ partition) O
(Leave a message if you need an invitation code)
Question 15th: separate numbers