如何优化此代码以缩短评估时间

时间:2018-05-30 06:42:08

标签: java algorithm

我正在解决一个问题,要求我打印一个整数数组中的所有数字,其中包含1,2,3。例如,包含[123,300,456,789]的数组将输出为[123,300]。 在我的代码中,我使用了ArrayList以及解决它所需的所有东西。评估时间仍未达标。

public static void take(int[] a) 
{
    ArrayList<Integer> ai = new ArrayList<>();
    for(int i=0; i<a.length;i++) 
    {
        int temp =a[i];
        while(a[i]>0) 
        {
            int b=a[i]%10;
            if(b==1||b==2||b==3) 
            {
                ai.add(temp);
                break;
            }
            a[i]= a[i]/10;
        }
    }
    if(ai.isEmpty()) 
    {
        System.out.println(-1);
    }
    else 
    {
        ai.sort(null);
        System.out.println(ai);
    }
}

public static void main(String[] args) 
{
    Scanner mew = new Scanner(System.in);
    int t=mew.nextInt();
    for(int i=0; i<t;i++) 
    {
        int n=mew.nextInt();
        int a[] = new int[n];
        for(int j=0; j<n;j++) 
        {
           a[j] = mew.nextInt();
        }
        take(a);
    }
}

4 个答案:

答案 0 :(得分:1)

您只需将number转换为字符串即可;检索所有字符并使用Set检查所需字符是否存在:

public static Set<Integer> take(int[] a, char[] markers) {
    Set<Integer> numbers = new TreeSet<>();

    for (int i = 0; i < a.length; i++) {
        String str = String.valueOf(a[i]);

        for (char marker : markers) {
            if (str.contains(String.valueOf(marker))) {
                numbers.add(a[i]);
                break;
            }
        }
    }

    return numbers;
}

另外,您可以使用流:

public static Set<Integer> take(int[] a, char[] markers) {
    return Arrays.stream(a)
                 .boxed()
                 .filter(val -> {
                     String str = String.valueOf(val);

                     for (char marker : markers)
                         if (str.contains(String.valueOf(marker)))
                             return true;

                     return false;
                 })
                 .sorted()
                 .collect(Collectors.toSet());
}

答案 1 :(得分:0)

如果我理解正确,您希望以文本方式搜索数字1,2或3是否至少存在1次。您可以使用这样的正则表达式执行此操作:

class MyCustomCell: UITableViewCell, BSCellProtocol {
     static var NibName: String! = "MyCustomCell"
     static var Identifier: String! = "cellIdentifier_at_Xib"

     @IBOutlet weak var lblTitle: UILabel!
     // other IBOutlet components
}

// In ViewController, register cell
tableView.registerCell(MyCustomCell.self)

// dequeue cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     // cell is `MyCustomCell` instance 
     let cell = tableView.dequeueCellWithType(MyCustomCell.self)

     // configure cell ...
     // ....

     return cell
}

我还将变量重命名为更清晰,并添加了额外的打印输出,以便在命令行的交互过程中获得反馈。

旁注:这样的事情应该通过单元测试进行测试,以确保所有情况都正常,而不必手动输入内容进行测试。

答案 2 :(得分:0)

你的目标严重过度复杂化。效率的第一条规则是&#34;避免做额外的工作&#34;。以下是代码运行过多的地方:

  • 您从输入中读取字符,将它们解析为整数,然后将数字分解为数字以检查每个字符对1,2和3
  • 你构建一个候选数组,然后测试数组的每个元素,但不需要数组本身,因为你只对通过1-2-3测试的候选人感兴趣。

我的代码避免了额外的工作,并使用稍微更有效的测试来检查是否存在1,2或3.这应该会带来显着的加速:

import java.util.*;

public class J {

    public static boolean has1or2or3(String s) {
        for (char c : s.toCharArray()) 
            if (c >= '1' && c <= '3') return true;
        return false;
    }

    public static void solve(Scanner in) {
        int cases = in.nextInt();
        while (cases-- > 0) {

            // read input, solve problem
            ArrayList<Integer> good = new ArrayList<>();
            int count = in.nextInt();
            for (int i=0; i<count; i++) {
                String candidate = in.next();
                if (has1or2or3(candidate)) {
                    good.add(Integer.parseInt(candidate));
                }
            }

            // generate output
            if (good.isEmpty()) {
                System.out.println(-1);
            } else {
                Collections.sort(good);
                for (int c : good) {
                    System.out.print(c + " ");
                }
                System.out.println();
            }
        }
    }

    public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            solve(in);
        }
    }   
}

示例输入和输出:

1
6
4567 345 1122 89458 8495 473
345 473 1122

答案 3 :(得分:-1)

为此使用散列... 使用key创建hashmap为1,2和3,这样就可以消除很多数字

相关问题