performance - What's making this program slow to process? (C++) -
#include <iostream> #include <vector> using namespace std; int main() { vector< int > number; bool numbersarecorrect = false; int input; while( cin >> input ) number.push_back( input ); vector< int > unique_number( number.size(), 0 ); vector< int > repeated( number.size(), 1 ); for( int = 0; < number.size(); i++ ) { for( int j = + 1; j < number.size() + 1; j++ ) { if( number[ ] != 0 && number[ ] == number[ j ] ) { repeated[ ]++; unique_number[ ] = number[ ]; } else unique_number[ ] = number[ ]; if( j == number.size() ) { for( int z = 0; z < number.size(); z++ ) { if( number[ z ] == unique_number[ ] ) number[ z ] = 0; } } } } for( int = 0; < number.size(); i++ ) { if( ( unique_number[ ] != 0 && repeated[ ] == 1 ) || ( unique_number[ ] != 0 && repeated[ ] % 2 != 0 ) ) { numbersarecorrect = false; cout << unique_number[ ] << endl; break; } else if( repeated[ ] == 1 ) numbersarecorrect = true; else if( repeated[ ] % 2 != 0 ) { numbersarecorrect = false; cout << repeated[ ] << endl; break; } else if( repeated[ ] % 2 == 0 ) numbersarecorrect = true; } if( numbersarecorrect == true ) cout << "0" << endl; return 0; }
this program gets positive integers user, checks if integer repeated 2k( even) times or 2k+1(odd) times. if latter true, prints integer , else prints 0; used 20000 inputs , takes more 10 seconds evaluate.. need know how make process faster. example input results in "0" : 1 2 2 1 , results in "3" : 1 2 2 1 3
how first sort thing. need single loop instead of 2 because find repetitions count consecutive occurrences.
failing use set or map. again you'll drop o(nlogn) instead of o(n^2).
Comments
Post a Comment