java - 有多少种方法不能构成三角形?

标签 java algorithm performance time time-limiting

给定 n 和一个 n 正整数数组,需要有多少种方法可以选择三个数字,使它们不能形成三角形。

示例:

3  
4 2 10

回答:

1

我的方法(在 JAVA 中)

int[] arr = new int[n];//list of the numbers given
int count=0;//count of all such triplets
for(int i=0;i<n;i++)
    arr[i]=sc.nextInt();
Arrays.sort(arr);
for(int i=n-1;i>=0;i--)
{
    int j=0;
    int k= i-1;
     while(j<k && k>=0)
     {
         if(arr[i]>=arr[j]+arr[k])//condition for no triangle formation
          {
              count++;
              j++;//checking the next possible triplet by varying the third number
          }
          else if(arr[i]<arr[j]+arr[k])
          {
              j=0;
              k--;//now varying the second number if no such third number exists
          }
     }
}
System.out.println(count);

我的算法:

对列表排序后,我试图找到所有小于 arr[i] 的数字,这样 arr[i]>=arr[j]+arr[k],在这种情况下三角形不会形成。

但是我正在为这个解决方案超时。谁能建议更好的方法来解决这个问题?

最佳答案

适当的伪代码是:

SORT array //nlogn
INT counter = n*(n-1)*(n-2)/6;
FOR i = n - 1; i >= 2; i-- DO //largest length in a triangle - there must be two lower
    currentLargestNumber = array[i];
    FOR j = i - 1; j >= 1; j-- DO
        BINARY SEARCH FOR SMALLEST k for which array[k] + array[j] > array[i]
        counter -= j - k;
        IF nothingAddedInTheLastIteration DO
            BREAK;
        END_IF
    END_FOR
    IF nothingAddedInTheLastIteration DO
        BREAK;
    END_IF
END_FOR

我假设不会有超过 3 个相同值的输入。如果有这种可能性,请删除不必要的值。

在每个循环中,您应该检查是否添加了任何三角形。如果不是,则打破此循环。

关于java - 有多少种方法不能构成三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38990766/

相关文章:

algorithm - 根据平均值选择不同的行组

java - 找出最长回文的长度。没有额外的数据结构是否可以做到这一点?

python - 迭代生成器和列表之间的速度差异

java - 当我尝试发布到我的 spring api 时 403 被禁止?

java - Eclipse 代码格式化程序 : Perform a single action

c++ - OBB(定向边界框)算法中的点?

performance - 让 Oracle 9i 使用索引

java - 在后台使用 Java 打开 URL

java - 鼠标悬停 - 在屏幕上显示消息 Java 应用程序

c++ - lambda 对象构建成本高吗?