为什么arraylist给出了错误的答案?

时间:2016-06-14 12:16:15

标签: java arrays arraylist

我有两组不同的代码,具有完全相同的逻辑。唯一的区别是使用arraylist代替arrays

扫描程序工作正常,arraylist给出了错误的答案。

scanner类和数组代码:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       int N = sc.nextInt();
       int[] A = new int[N];
       int[] B = new int[N];
       int ans = 0;
       boolean[] visited = new boolean[N];
       for (int i = 0; i < N; i++) {
           A[i] = sc.nextInt();
       }
       for (int i = 0; i < N; i++) {
           B[i] = sc.nextInt();
       }
      for (int i = 0; i < N; i++) {
          for (int j = 0; j < N; j++) {
              if (A[i] == B[j] ) {
                B[j]=0;
                  ans++;
                    break;
                 }
            }
        }
        if (ans < N)
            System.out.println(ans + 1);
        else if (ans == N) {
            System.out.println(ans - 1);
        }
    }
 }

bufferedreadernad arraylist code:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) throws IOException {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        ArrayList<Integer> al=new ArrayList<Integer>();
        ArrayList<Integer> bl=new ArrayList<Integer>();
    int T=Integer.parseInt(br.readLine());
    int count=0;
    int x=0;
     String[] s=br.readLine().split(" ");
        for(int i=0;i<T;i++){
            al.add(Integer.parseInt(s[i]));
        }
        String[] s1=br.readLine().split(" ");
        for(int j=0;j<T;j++){
            bl.add(Integer.parseInt(s1[j]));
        }
        for(int i=0;i<T;i++){
            for(int j=0;j<T;j++){
            if(al.get(i)==bl.get(j)){
                bl.set(j,0);
                count++;
                break;
            }
            }
        }
        if(count==T){
            System.out.println(count-1);
        }
        else if(count<T){
            System.out.println(count+1);

        }
    }
 }

0 个答案:

没有答案