What if the question is asking for the first N primes (like 200)


  • 0
    B

    Apparently, creating a fixed length array would not work. My idea is to use ArrayList. Here is my solution for the num of primes less than N. Same idea could be applied to get first 200 primes. It will return a time limit exceed for current test cases.

    public class Solution {
    public int countPrimes(int n) {
        ArrayList<Integer> primes=new ArrayList<Integer>();
        if(n<2) return 0; 
        primes.add(2);
        for(int i=2; i<n+1;i++)
        {   
            for(int j=0;j<primes.size();j++ )
            {
                if(i%primes.get(j)==0)
                break;
                if(i%primes.get(j)!=0&&j==primes.size()-1)
                primes.add(i);
                
            }
        }
        return primes.size();
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.