- Practice
- Data Structures
- Arrays
- Sparse Arrays
- Discussions
Sparse Arrays
Sparse Arrays
+ 0 comments Well, sadly, this problem isn't really about sparse arrays or whatever intention was. It's silly. If you read this comment, then i'm pretty sure, you have the same opinion. I propose to have some fun! Let's write shortest/cleanest code which solves this stuff in our favourite languages. Here's my for java8 :P
public static void main(String[] args) { Scanner in = new Scanner(System.in); List<String> strings = IntStream.range(0, in.nextInt()).mapToObj(i -> in.next()).collect(Collectors.toList()); IntStream.range(0, in.nextInt()).mapToObj(i -> in.next()).mapToLong(q -> strings.stream().filter(q::equals).count()).forEach(System.out::println); }
+ 0 comments Come on guys =) why you think of it as the fewer lines or seconds you spent — you reach the better solution? This challenge is about fundamental computer science techniques, google about Sparse Arrays and make a decision why this challenge is named so (this is not without purpose). Believe me it's interesting and valuable =) HashMap is the right pill here and of course we would hardly find any programming language not giving HashMaps out of the box. But how HashMaps actually work under the hoods? Go through this!
+ 0 comments This challenge is categorized as "Difficult"? I solved it in just a few minutes using a straight-ahead O(n^2) loop and it worked. Then I went back and re-did it with an associative array (hash map) in just a few more minutes and it worked as well. I don't think I learned anything about data structures or sparse arrays.
+ 0 comments Here is my simple code for this:
int main() { int n,i,m,j; cin>>n; string s[n]; for(i=0;i<n;i++) { cin>>s[i]; } cin>>m; string t[m]; for(i=0;i<m;i++) { cin>>t[i]; } for(i=0;i<m;i++) { int flag=0; for(j=0;j<n;j++) { if(t[i]==s[j]) flag++; } cout<<flag<<"\n"; } return 0; }
+ 0 comments I feel this is the simplest approach to this problem.
public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); String[] a = new String[N]; for(int i=0; i<N; i++){ a[i] = sc.next(); } int Q = sc.nextInt(); int[] result = new int[Q]; int i=0; while(sc.hasNext()){ String query = sc.next(); int count = 0; for(int j=0; j<N; j++){ if (a[j].equals(query)){ count++; } } result[i++] = count; } for(i=0; i<Q; i++){ System.out.println(result[i]); } } }
Sort 1587 Discussions, By:
Please Login in order to post a comment