2013-03-19 45 views
2

我有相同的ElemList類上定義http://www.cplusplus.com/forum/beginner/73928/檢查所有值都重複至少兩次在鏈表

您能否提供關於如何寫的情況下,返回true所有功能的一些技巧的價值已被重複兩次或更多次?例如。

1,1,1,2,2 - true 
1,2 - false 

我有點覺得它肯定會需要一個動態數組,但不能想到算法。

+0

那麼非連續的重複呢? '1,2,1,2',是「真」還是「假」? – jrok 2013-03-19 12:57:12

+0

這將是正確的反應,不需要排序的元素。 – waplet 2013-03-19 13:01:25

回答

2

是的,做一個std::map<int,int>你在哪裏計算列表中每個數字的發生次數。這個計算需要一次遍歷所有列表。

之後,再拍過你剛剛創建的std::map,看看所有的值都大於或等於2

0

功能看起來像這樣(未經):

std::map<int,int> m_mapCount; 
    std::map<int,int>::iterator m_Iterator; 

    for (l.start(); !l.end(); l.next()) // put the content of your linkedlist to map 
    { 
     m_mapCount[l.current->num] += 1; 
    } 

    for (m_Iterator=m_mapCount.begin(); m_Iterator!=m_mapCount.end(); m_Iterator++) 
    { 
     if(m_Iterator->second >= 2) return true; 
    } 
0
bool twoormore() 
    { 
     int count = 0;// for counting elements in list 
     int temp;// temprorary element for sorting and logical part 
     int cik;// how much times the value has been mentioned 
     bool res = true;// function result 
     int * arr;// pointer for the upcoming dynamic array 
     for(start();!end();next()) 
     { 
      count++;// counting the elements 

     } 
     if(count != 0){ 
      arr = new int[count];//creating array 
      int i = 0; 
      for(start();!end();next()) 
      { 
       arr[i++] = current->num;//filling array 
      } 
      /** array sorting **/ 
      for(int i = 0;i < count;i++) 
       for(int j = 0; j < count; j++) 
       { 
        if(arr[j] > arr[i]) 
        { 
         temp = arr[i]; 
         arr[i] = arr[j]; 
         arr[j] = temp; 
        } 
       } 
      /** sort ends **/ 
      temp = arr[0]; // setting first element ar temp.. for upcoming check 
      cik = 1;// it's been its first time 
      for(int i = 1;i < count;i++) 
      { 
       if(arr[i] == temp) 
       { 
        cik++; continue;// if upciming element is equal to temprorary , then add 1 to counter.. and continue looping 
       }else 
       { 
        if(cik > 1) 
        { 
         temp = arr[i];// if everything ok, but element value changes. 
         cik = 1;// sets defualt 
         continue; 
        } 
        else 
        { 
         res = false;// other way, the value wasnt there two times 
         break; 
        } 
       } 


      } 
      delete arr;//deleting allocated space for array 
      return res;// returning bool, true or false. 
     } 
    }