查找在数组中连续出现最多次数的值

时间:2017-02-09 16:21:50

标签: java arrays performance loops time

以下代码在java lang中:

d3.symbolCross

我需要做的是找到连续发生超过k次的值(在这种情况下为3)。 #include <iostream> #include <fstream> using namespace std; int main(int argc, char *argv[]) { cout << argv[0]; //ONLY WANT TO RUN TILL HERE for(int x = 1; x < argc; x++) { string s(argv[x]); if( } return 0; } 只能有一个值,如果不存在此值,则int[] array = {1,2,2,3,3,3,2,2,1}; int k = 2;

说明:
1连续1次出现。第2次发生2次,但不是> k。发生3次,即> k。因为,只有一个可能的答案,您可以停止在其他值中搜索答案并打印3.
代码的时间限制为0.25秒

更新:到目前为止我尝试了什么

occurs>k

当我尝试通过此解决大约10个查询时,需要2秒钟。我必须在1中完成它。你能建议一些优化代码的方法,以便我可以研究它然后重试。

1 个答案:

答案 0 :(得分:1)

您不需要使用while循环和lo

遍历两次

1。)使用循环遍历

2。)如果跟踪元素序列

3。)如果元素发生变化,请重置曲目

4。)当赛道达到k以上时,打破循环

    int[] array = {1,2,2,3,3,3,2,2,1};
    int k = 2;
    // get first element
    int element=array[0];

    // set tot to 1 
    int tot=1;
        for (int i = 1; i < array.length; i++) {
            // if values are same , increment tot
            if (element==array[i]) {
                tot++;
            }else {
                // set element to new found value and tot = 1
                element=array[i];
                tot=1;
            }
            // when any elements exceeds the k limit 
            // print element and stop the loop
            if (tot>k) {
                System.out.println(array[i]);
                break;
            }
        }
        // to print -1 if tot > k never reached
        if (!(tot>k)) {
            System.out.println(-1);
        }
相关问题