Example #1
0
        public IList <int> CountSmaller(int[] nums)
        {
            int[] result = new int[nums.Length];
            SortedDictionary <int, List <int> > dict = new SortedDictionary <int, List <int> >();

            for (int i = 0; i < nums.Length; i++)
            {
                List <int> l;
                if (!dict.TryGetValue(nums[i], out l))
                {
                    dict.Add(nums[i], l = new List <int>());
                }
                l.Add(i);
            }
            SegmentTree tree = new SegmentTree(0, nums.Length - 1);

            foreach (var pair in dict)
            {
                foreach (int pos in pair.Value)
                {
                    result[pos] = tree.CountRange(pos + 1, nums.Length - 1);
                }
                foreach (int pos in pair.Value)
                {
                    tree.Add(pos);
                }
            }
            return(result.ToList());
        }
Example #2
0
 public IList<int> CountSmaller(int[] nums)
 {
     int[] result = new int[nums.Length];
     SortedDictionary<int, List<int>> dict = new SortedDictionary<int, List<int>>();
     for (int i = 0; i < nums.Length; i++)
     {
         List<int> l;
         if (!dict.TryGetValue(nums[i], out l))
         {
             dict.Add(nums[i], l = new List<int>());
         }
         l.Add(i);
     }
     SegmentTree tree = new SegmentTree(0, nums.Length - 1);
     foreach (var pair in dict)
     {
         foreach (int pos in pair.Value)
         {
             result[pos] = tree.CountRange(pos + 1, nums.Length - 1);
         }
         foreach (int pos in pair.Value)
         {
             tree.Add(pos);
         }
     }
     return result.ToList();
 }
Example #3
0
 public int CountRange(int l, int r)
 {
     if (l > r || l > e || r < s || count == 0)
     {
         return(0);
     }
     if (l < s)
     {
         l = s;
     }
     if (r > e)
     {
         r = e;
     }
     if (l == s && r == e)
     {
         return(count);
     }
     return(left.CountRange(l, r) + right.CountRange(l, r));
 }