【问题标题】:Reduce Time complexity of the following program降低以下程序的时间复杂度
【发布时间】:2015-12-01 00:57:08
【问题描述】:
import java.util.Scanner;
class Special_Pairs{

private static Scanner scan;


public static void main(String [] args) {
    byte t;
    int n;
    scan = new Scanner(System.in);
    t=scan.nextByte();
    int[] a=new int[100000];
    while(t>0)
    {
        int i,j,count=0;
        n=scan.nextInt();
    for(i=0;i<n;i++)
    {
        a[i]=scan.nextInt();
    }
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            if(((a[i]&a[j])==0)||((a[j]&a[i])==0))
            {
                count++;
            }
        }
    }
    t--;
    System.out.println(count);
    }       
}
}

帮我降低这个程序的时间复杂度

问题:

你得到了一个大小为 N 的整数数组 A。你必须报告有序对的数量 (i,j) 使得 A[i] &amp; A[j]=0。 这里&amp; 表示BITWISE AND (i,j)(j,i) 被认为是不同的。

输入: 第一行包含 T-Number of Test Cases。每个测试的第一行包含 N。下一行包含 N 个整数 - 第 i 个整数 A[i]。

输出:为每个测试用例输出这样对的数量。

约束: T ≤ 10; N≤100000; A[i] ≤ 1000000

示例输入(明文链接)

1 5 41 47 34 40 29

样本输出(明文链接)

2

解释:这些是必需的(3 5)(5 3)

【问题讨论】:

  • 欢迎来到 StackOverflow,这不是一个代码编写/家庭作业解决服务,表现出一些努力。到目前为止,您尝试过什么?

标签: time time-complexity reduce


【解决方案1】:

我会为此建议三个优化。我也修改了代码。

  1. 对于外循环的每次迭代,您不必总是从 0 开始。第二个循环可以从第一个循环的current+1 开始。所以不会比较您已经比较过的元素。
  2. 您无需检查(i,j)(j,i) 这两对。如果一个为零,那么另一个将始终为零。
  3. 您不需要用固定大小初始化数组。您始终可以读取 n 的值来初始化它。
import java.util.Scanner;

public class Pairs {
  public static void main(String [] args) {
    Scanner scan = new Scanner(System.in);
    int t = scan.nextInt();
    while(t > 0) {
      t--;
      int count = 0;
      int n = scan.nextInt();
      int a[] = new int[n];
      for(int i = 0; i<n; i++) {
        a[i]=scan.nextInt();
      }
      for(int i = 0; i<n-1; i++) {
        for(int j = i+1; j<n; j++) {
          if((a[i] & a[j])==0)
          {
            count += 2;
          }
        }
      }
      System.out.println(count);
    }
  }
}

【讨论】:

  • 2.你不需要同时测试(a[i]&amp;a[j])==0(a[j]&amp;a[i])==0。只有一个就足够了。 (哦,伙计,你编辑的速度比我输入答案的速度还要快。呵呵)
【解决方案2】:

如果您正在参加编程比赛(如 ICPC 或类似的比赛),也许您不应该使用 Scanner。从键盘读取太慢了。我已经参加过 ICPC,但我曾经使用 C++。也许你应该试试BufferedReader 而不是Scanner

【讨论】:

    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 2016-01-08
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多