数组中数目最多的三个数 2.3

是数组中超过一半数目问题的升级版,但万变不离其中

   

声明一个time数组和candidate数组,长度为3,分别存放三个数的次数和数字

   

首先次数声明为0,数字声明为不存在的数,这里暂时声明为-1,其实应该声明为一个不存在的数字

   

然后遍历数组

   

如果该数是第一个candidate,第一个candidatetime++

如果是第二个,那么第二个time++;

   

然后也判断三个candidatetime是否达到0,如果达到,将更新candidate,更新为当前数字

   

最后返回candidate数组

   

package moreThanHalfNum29;

   

public class MostThreeNum29 {

   

static int[] Find(int[] a) {

int N = a.length;

int ID_NULL = -1;

;// 定义一个不存在的ID

int[] nTimes = new int[3];

int i;

nTimes[0] = nTimes[1] = nTimes[2] = 0;

int[] candidate = new int[3];

candidate[0] = candidate[1] = candidate[2] = ID_NULL;

for (i = 0; i < N; i++) {

if (a[i] == candidate[0]) {

nTimes[0]++;

} else if (a[i] == candidate[1]) {

nTimes[1]++;

} else if (a[i] == candidate[2]) {

nTimes[2]++;

} else if (nTimes[0] == 0) {

nTimes[0] = 1;

candidate[0] = a[i];

} else if (nTimes[1] == 0) {

nTimes[1] = 1;

candidate[1] = a[i];

} else if (nTimes[2] == 0) {

nTimes[2] = 1;

candidate[2] = a[i];

} else {

nTimes[0]--;

nTimes[1]--;

nTimes[2]--;

}

}

return candidate;

}

   

public static void main(String[] args) {

// TODO Auto-generated method stub

int[] a = { 2, 2, 3, 3, 4, 5, 5, 6 };

int[] result = Find(a);

for (int i = 0; i < result.length; i++) {

System.out.println(result[i]);

}

}

   

}

posted @ 2015-04-05 19:50  keedor  阅读(194)  评论(0编辑  收藏  举报