码迷,mamicode.com
首页 > 编程语言 > 详细

其他数出现两次的数组中三个只出现一次的数

时间:2016-01-06 11:33:44      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <stdlib.h>
//#include <algorithm>

/*
	注:algorithm是C++头文件,不能用于纯C中
*/

typedef struct
{
	int num1;
	int num2;
	int num3;
}ThreeNumber;

int isOdd(int num);
int cmp(const void *a, const void *b);
ThreeNumber getThreeNumber(int *arr,int length);

int main() {
	int length = 0;	//整数个数
	scanf("%d", &length);
	if (!isOdd(length))	//判断是否是奇数
		printf("Please input an odd number.\n");
	else{
		int * numbers = (int*)malloc(length * sizeof(int));	//存储这length个整数
		printf("Please input %d number: \n", length);
		int tmp;
		for (int i = 0; i < length; ++i){
			scanf("%d", &tmp);
			numbers[i] = tmp;
		}
		ThreeNumber threeNumber = getThreeNumber(numbers, length);
		printf("%d %d %d\n", threeNumber.num1, threeNumber.num2, threeNumber.num3);
	}
	system("pause");
	return 0;
}

ThreeNumber getThreeNumber(int *arr, int length){
	qsort(arr, length, sizeof(int), cmp);
	int nums[3];
	int index = 0;
	for (int i = 0; i < length - 1; ++i){
		if (arr[i] == arr[i + 1]){
			++i;
		}
		else
			nums[index++] = arr[i];
	}
	if (index == 2)
		nums[index] = arr[length - 1];
	ThreeNumber threeN;
	threeN.num1 = nums[0];
	threeN.num2 = nums[1];
	threeN.num3 = nums[2];
	return threeN;
}

int cmp(const void *a, const void *b){
	return *(int*)a - *(int*)b;	//不甚懂
}

int isOdd(int num){
	if (num % 2 == 0)
		return 0;
	else
		return 1;
}

  

其他数出现两次的数组中三个只出现一次的数

标签:

原文地址:http://www.cnblogs.com/mutaohengheng/p/5104790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!