思路分析:类似快速排序的处理。可以用两个指针分别指向数组的头和尾,头指针正向遍历数组,找到第一个偶数,尾指针逆向遍历数组,找到第一个奇数,使用引用参数传值交换两个指针指向的数字,然后两指针沿着相应的方向继续向前移动,重复上述步骤,直到头指针大于等于尾指针为止。代码如下:#include "stdafx.h"#include using namespace std;void Swap(int& a, int& b){ int temp = a; a = b; b = temp;}void ReverseArray(int arr[], int len){ if Read More
posted @ 2014-03-10 23:55 源子陌 Views(1474) Comments(0) Diggs(0)
思路分析:尼玛这不就是等差数列么。首先将该n-1个整数相加,得到sum,然后用(1+n)n/2减去sum,得到的差即为缺失的整数。因为1~n一共n个数,n个数的和为(1+n)n/2,而未排序数列的和为sum,二者之差即为确实的数。程序示例如下:#include "stdafx.h"#include #define MAX 5int main(){ int array[MAX] = { 3, 2, 1, 6, 4 }; int i; int sum = 0; int temp; for (i = 0; i < MAX; i++) sum += i; temp = (MA Read More
posted @ 2014-03-10 16:59 源子陌 Views(450) Comments(0) Diggs(0)
方法一:枚举法。该方法是最容易、也是最简单的方法,枚举出数组A和数组B中所有的元素对,判断其和是否为c,如果是,则输出。方法二:排序+二分查找法。首先,对两个数组中长度较大数组,不妨设为A,排序;然后,对于B中每个元素B[i]在A中二分查找c-B[i],如果找到,直接输出。方法三:排序+线性扫描法。首先,对A和B进行排序;然后用指针p从头扫描A,用指针q从尾扫描B,如果A[p]+B[q]==c,则输出A[p]+B[q],且p++,q--;如果A[p]+B[q]>c,则q--;否则p++。代码如下:#include "stdafx.h"#include void sor Read More
posted @ 2014-03-10 16:06 源子陌 Views(1270) Comments(0) Diggs(0)
一个整数数组,元素取值可能是1~N(N是一个较大的正整数)中的任意一个数,相同数值不会重复出现。设计一个算法,找出数列中符合条件的数对,满足数对中两数的和等于N+1。方法一:蛮力法。这是最简单的方法,枚举出数组中所有可能的数对,看其和是否为N+1,如果是,则输出。但这种方法一般效率不高。代码如下:#include "stdafx.h"#include int findCouple(int a[], int n, int &val){ if (a == NULL || n max) max = a[m]; } for (int i = 0; i N+1,则back-- Read More
posted @ 2014-03-10 10:51 源子陌 Views(1566) Comments(0) Diggs(0)