Exemplo n.º 1
0
        /// <summary>
        /// 在给定的一组数据中,所有和为0的整数对的数量
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        public static int TwoSumCount(int[] a)
        {
            Array.Sort(a);
            int n     = a.Length;
            int count = 0;

            for (int i = 0; i < n; i++)
            {
                if (Foreword.Rank(-a[i], a) > i)
                {
                    count++;
                }
            }

            return(count);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 所有三个数和为0的组合数
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        public static int ThreeSumCount(int[] a)
        {
            Array.Sort(a);
            int n     = a.Length;
            int count = 0;

            for (int i = 0; i < n; i++)
            {
                for (int j = i + 1; j < n; j++)
                {
                    if (Foreword.Rank(-(a[i] + a[j]), a) > j)
                    {
                        count++;
                    }
                }
            }
            return(count);
        }
Exemplo n.º 3
0
        /// <summary>
        /// 返回大小为参数m的数组,其中第i个元素的值为整数i在参数数组中出现的次数
        /// </summary>
        /// <param name="array"></param>
        /// <param name="m"></param>
        /// <returns></returns>
        public static int[] Histogram(int[] array, int m)
        {
            int[] result = new int[m];
            Array.Sort(array);//先对该数组排序
            for (int i = 0; i < m; i++)
            {
                int index = Foreword.Rank(i + 1, array);//用二分查找法找出该数在数组中的位置
                if (index == -1)
                {
                    result[i] = 0;
                }
                else
                {
                    result[i] = GetCountInSortedArray(array, index);
                }
            }

            return(result);
        }