c# - How to calculate the time complexity of this odd method -
the method is:
list<book> books = new list<book>(); public list<book> shoot() { foreach(var b in books) { bool find = true; foreach(var otherb in books) { if(otherb != b && otherb.author == b.author) { find = false; } } if(find) { yield return b; } } }
normally, time complexity o(books.count^2), there if(find) statement in outer loop , may change loop times.
so questions are:
- what time complexity of method?
- how did calculate it?
i'm waiting online answer.
thank in advance.
you go through each book in outer loop (n) , each outer book go through each otherb in inner loop (n times) the time complexity o(n^2).
the yield return not change complexity of algorithm, creates iterator pattern if traverse whole list calling function, go through iterations in algo.
what yield keyword used in c#?
to optimize algorithm, btilly mention, 2 passes on collection, on first pass store number of books per author in hash table , on second pass check if author has more 1 book using hash table (assuming constant time lookup) , yield book if does:
public list<book> shoot() { var authors = new dictionary<string, int>(); foreach(var b in books) { if(authors.containskey(b.author)) authors[b.author] ++; else authors.add(b.author, 1); } foreach(var b in books) { if(authors[b.author] == 1) yield return b; } }
this way have linear time complexity of o(n), note need o(n) space in case.
Comments
Post a Comment