• 微软面试题,倒置数组


    View Code
    namespace ConsoleApplication1
    {
        /// <summary>
        /// 微软面试题,一整数数组{1,2,3……}
        /// 选择其中某个数,然后将次数放置数组末尾,
        /// 比此数大的数放在数组前端递增排列
        /// 在后面添加比次数小的数,递增排列
        /// </summary>
        class Program
        {
            static void Main(string[] args)
            {
                //设定数组值为{1-20}
                int[] intArr = new int[20];
                for (int i = 0; i < intArr.Length; i++)
                {
                    intArr[i] = i + 1;
                }
    
                //获取用户选择的数字
                Console.WriteLine("SelectElements(1-20):");
                int selectElement=Convert.ToInt32( Console.ReadLine());
    
                Func1(intArr,selectElement);
    
                Console.Read();
            }
    
            /// <summary>
            /// 输出重整序列的数组
            /// </summary>
            /// <param name="arr"></param>
            /// <param name="selectElement"></param>
            public static void Func1(int[] arr, int selectElement)
            {
                int index = -1;
                Swap(arr, 0, arr.Length - 1);
                for (int i = 0; i < arr.Length; i++)
                {
                    if (arr[i] == selectElement)
                        index = i;
                }
    
                Swap(arr,0,index-1); 
                Swap(arr, index, arr.Length - 1);
                
                for (int i = 0; i < arr.Length; i++)
                {
                    Console.WriteLine(arr[i].ToString());
                }
            }
            
            /// <summary>
            /// 倒置数组中某段的值
            /// </summary>
            /// <param name="arr"></param>
            /// <param name="beginIndex"></param>
            /// <param name="endIndex"></param>
            public static void Swap(int[] arr, int beginIndex, int endIndex)
            {
                int temp = -1;
                int swapTimes = -1;
    
                if ((endIndex - beginIndex + 1) % 2 == 0)
                    swapTimes = (endIndex - beginIndex + 1) / 2;
                else
                    swapTimes = (endIndex - beginIndex) / 2;
    
                for (int i = 0; i < swapTimes; i++)
                {
                    temp = arr[beginIndex + i];
                    arr[beginIndex + i] = arr[endIndex - i];
                    arr[endIndex - i] = temp;
                }
            }
        }
    }
  • 相关阅读:
    如何查看操作系统的具体版本号
    Review of Image Super-resolution Reconstruction Based on Deep Learning
    opencv imshow图片显示不全
    Javaweb文件下载异常
    Microsoft Edge出现错误代码:STATUS_INVALID_IMAGE_HASH
    Javaweb导入excel数据
    Java读取execl数据
    浏览器网页左上角小图标实现方式
    Java LDAP验证
    Java JPA新增数据生成UUID
  • 原文地址:https://www.cnblogs.com/maomiyouai/p/2972591.html
Copyright © 2020-2023  润新知