Getting indexes of maximum number in array

心不动则不痛 提交于 2019-12-04 06:39:29

One approach would be to simply make a single pass along the array and keep track of all indices of the highest number. If the current entry be less than the highest number seen so far, then no-op. If the current entry be the same as the highest number seen, then add that index. Otherwise, we have seen a new highest number and we should throw out our old list of highest numbers and start a new one.

int[] data = {0,4,2,0,1,0,4,2,0,4,0,2};
int max = Integer.MIN_VALUE;
List<Integer> vals = new ArrayList<>();

for (int i=0; i < data.length; ++i) {
    if (data[i] == max) {
        vals.add(i);
    }
    else if (data[i] > max) {
        vals.clear();
        vals.add(i);
        max = data[i];
    }
}

You are on the Stream- way... I would suggest you to stay there :)

int[] data = { 0, 4, 2, 0, -1, 0, 4, 2, 0, 4, 0, 2 };
int max = Arrays.stream(data).max().getAsInt();
int[] indices = IntStream.range(0, data.length).filter(i -> data[i] == max).toArray();

As i see your program goes through the array 2 times.You can try this: Run through the array finding the max of this array.When you find a max just save every other element that is equal to the current max and their values.This way you only go through the array only once. Here is an example: Let's say you have the following array {1,3,5,3,4,5} and you go through it.You will first save the 1 as max then the 3 then the 5 which is the max of this array.After saving 5 you won't save 3 or 4 but you will save 5 as it is equal to the max.Hope i helped.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!