在Count排序数组中查找中间元素

Joh*_*Dow 0 java sorting algorithm

所以,我有这样的数组:

a[1] = 2
a[4] = 3
a[8] = 1
Run Code Online (Sandbox Code Playgroud)

代表这个序列 1 1 4 4 4 8

我需要找到中间元素或元素(奇数和偶数); 在这个例子中它是4.

我怎么能这么快?

我的代码很慢:

static int B(int[] array, int size) {       
    int c = 0;
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i]; j++) {
            c++;
            if (c == size / 2) {
                return i;    
            }
        }
    }   
}
Run Code Online (Sandbox Code Playgroud)

noM*_*MAD 5

  1. 遍历原始数组并添加所有值

    a[1] = 2
    a[4] = 3
    a[8] = 1
    sum = 6
    
    Run Code Online (Sandbox Code Playgroud)
  2. 除以2(找到中间)

    mid = 6/2 = 3
    
    Run Code Online (Sandbox Code Playgroud)
  3. 遍历原始数组并从sum中减去值

    check if ans <= 0
    if true print index
    else continue to next
    
    Run Code Online (Sandbox Code Playgroud)