[LintCode 382]给定一个整数数组,在该数组中,寻找三个数,分别代表三角形三条边的长度,问,可以寻找到多少组这样的三个数来组成三角形?

样例

例如,给定数组 S = {3,4,6,7},返回 3

其中我们可以找到的三个三角形为:

{3,4,6} {3,6,7} {4,6,7}

给定数组 S = {4,4,4,4}, 返回 4

其中我们可以找到的三个三角形为:

{4(1),4(2),4(3)} {4(1),4(2),4(4)} {4(1),4(3),4(4)} {4(2),4(3),4(4)}

        /**
       * @param S: A list of integers
       * @return: An integer
       */
       //Solution 1 , 满足要求,但是时间复杂度不符合要求,为 O(n^3),测试提示超时
        int triangleCount1( vector < int > & S ) {
               // write your code here
               int iSize = S .size();
               if (iSize <= 2)
              {
                      return 0;
              }
              
               int sum = 0;
               for ( int i = 0; i < iSize - 2; i++)
              {
                      int a = S .at(i);
                      for ( int j = i + 1; j < iSize - 1; j++)
                     {
                            int b = S .at(j);
                            for ( int k = j + 1; k < iSize; k++)
                           {
                                   int c = S .at(k);
                                   if (a + b > c && a + c > b && b + c > a)
                                         sum++;
                           }
                     }
              }
              cout << "sum = " << sum;
               return sum;
       }

//Solution 2 , 优化算法, 使时间复杂度为O(n^2),总体思路为先将vector 进行排序,然后三角形的判断条件就可以是最小两边之和大于第三边,这样就能少一轮遍历
        int triangleCount( vector < int > & S ) {
               // write your code here
               int iSize = S .size();
               if (iSize <= 2)
              {
                      return 0;
              }
               int sum = 0;
              sort( S .begin(), S .end());
               for ( int i = 2; i < iSize; i++)
              {
                      int posLeft = 0;
                      int posRight = i - 1;
                      int c = S .at(i);
                      while (posLeft < posRight)
                     {
                            if ( S .at(posLeft) + S .at(posRight) <= c)
                                  posLeft++;
                            else if ( S .at(posLeft) + S .at(posRight) > c)
                           {
                                  sum += posRight - posLeft;
                                  posRight--;
                           }
                                  
                     }
              }
               return sum;
       }


你可能感兴趣的:(LintCode,C++)