Exemplo n.º 1
0
        //For input of size n and output of size m, this approach takes O(n + m log n)
        //Space complexity O(m)
        public static List <int> GetBoxWeight(List <int> weights)
        {
            //[3,7,5,6,2] sum=23
            // 23/2 = 11

            //Heap
            //   7
            //  6  5
            //3  2
            int target = weights.Sum() / 2;

            PQ <int> pq = new PQ <int>(false);

            pq.AddAll(weights.ToArray());
            int        curSum = 0;
            List <int> res    = new List <int>();

            while (curSum <= target)
            {
                int val = pq.Dequeue();
                curSum += val;
                res.Insert(0, val);
            }
            return(res);
        }
Exemplo n.º 2
0
        public static List <String> topMentioned(int k, List <String> keywords, List <String> reviews)
        {
            List <string> result = new List <string>();

            //:? non capturing expression
            //\\b \\b  match a block of word not word part of other string or punctuation;

            string s = "\\b(:?" + String.Join("|", keywords) + ")\\b";
            Regex  r = new Regex(s, RegexOptions.IgnoreCase);

            Dictionary <string, int> dict = new Dictionary <string, int>();

            foreach (string review in reviews)
            {
                MatchCollection matches = r.Matches(review);

                HashSet <string> words = new HashSet <string>();
                foreach (Match m in   matches)
                {
                    words.Add(m.Value.ToLower());
                }
                foreach (string w in words)
                {
                    if (!dict.ContainsKey(w))
                    {
                        dict.Add(w, 1);
                    }
                    else
                    {
                        dict[w]++;
                    }
                }
            }

            PQ <string> pq = new PQ <string>(Comparer <string> .Create((a, b) => (dict[a] == dict[b])? a.CompareTo(b): dict[a] - dict[b]));

            foreach (var item in dict)
            {
                if (pq.Count() < k)
                {
                    pq.Enqueue(item.Key);
                }
                else
                {
                    if (item.Value > dict[pq.Peek()])
                    {
                        pq.Dequeue();
                        pq.Enqueue(item.Key);
                    }
                }
            }

            while (pq.Count() != 0)
            {
                result.Insert(0, pq.Dequeue());
            }

            return(result);
        }