zoukankan      html  css  js  c++  java
  • 排序数组中重复最对的数字长度

    题目:在 1,2,2,3,3,3,4,5,5,6中1,2.2,3.3.3,4,5.5,6都是平台。试编写一个程序,接受一个数组,把这个数组中最长的平台找出来。在上面的例子中就是3.3.3就是该数组中最长的平台。 

    分析:排序给我们带来的好处是在o(n)的时间复杂度就能解决这个问题。下面看代码:

    #include <iostream>
    #include <cassert>
    using namespace std;
    
    int FindLongestArraySolution1(int arr[],int len)
    {
    	assert(arr && len>=0);
    	int maxLen = 0x80000000;
    	int sublen = 1;
    	for(int i=1; i<len; ++i){
    		if(arr[i]==arr[i-1]){
    			++sublen;
    			maxLen = sublen>maxLen?sublen:maxLen;
    		}
    		else
    			sublen = 1;
    	}
    	return maxLen;
    }
    
    int main()
    {
    	const int size = 10;
    	int arr[size]={1,2,2,2,3,3,3,3,5,5};
    	cout<<FindLongestArraySolution1(arr,size)<<endl;
    	system("pause");
    	return 0;
    }


        那么怎么用最短的代码,最少的变量来实现这个问题呢,需要思考一下,下面看代码;

    #include <iostream>
    #include <cassert>
    using namespace std;
    
    int FindLongestArraySolution2(int arr[],int len)
    {
    	assert(arr && len>=0);
    	int sublen = 1;
    	for(int i=1; i<len; ++i){
    		if(arr[i]==arr[i-sublen])
    			++sublen;
    	}
    	return sublen;
    }
    
    int main()
    {
    	const int size = 10;
    	int arr[size]={1,2,2,2,3,3,3,3,5,5};
    	cout<<FindLongestArraySolution2(arr,size)<<endl;
    	system("pause");
    	return 0;
    }


  • 相关阅读:
    UVAlive5135_Mining Your Own Business
    UVAlive3523_Knights of the Round Table
    UVA10759_Dice Throwing
    POJ3177_Redundant Paths
    UVA11027_Palindromic Permutation
    Codechef_JULY14
    UVAlive4255_Guess
    UVA10054_The Necklace
    杜教BM
    【2018徐州网络赛】Morgana Net (矩阵快速幂)
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3359952.html
Copyright © 2011-2022 走看看