华为上机练习题--按照新规则排序
来源:互联网 发布:报警回执Ps软件 编辑:程序博客网 时间:2024/06/05 23:49
* 给定一个数组input[] ,如果数组长度n为奇数,
* 则将数组中最大的元素放到 output[] 数组最中间的位置,
* 如果数组长度n为偶数,
* 则将数组中最大的元素放到 output[] 数组中间两个位置偏右的那个位置上,
* 然后再按从大到小的顺序,依次在第一个位置的两边,
* 按照一左一右的顺序,依次存放剩下的数。
* 例如:
* input[] = {3, 6, 1, 9, 7}
* output[] = {3, 7, 9, 6, 1};
* input[] = {3, 6, 1, 9, 7, 8}
* output[] = {1, 6, 8, 9, 7, 3}
分析: 题目虽然新规定了排列规则, 但是还是存在大小顺序的, 所以我们可以先对数组先进行排序, 然后再将排好序的数组重新按照规则再组合
代码如下:
package com.wenj.test;
/*
* 给定一个数组input[] ,如果数组长度n为奇数,
* 则将数组中最大的元素放到 output[] 数组最中间的位置,
* 如果数组长度n为偶数,
* 则将数组中最大的元素放到 output[] 数组中间两个位置偏右的那个位置上,
* 然后再按从大到小的顺序,依次在第一个位置的两边,
* 按照一左一右的顺序,依次存放剩下的数。
* 例如:
* input[] = {3, 6, 1, 9, 7}
* output[] = {3, 7, 9, 6, 1};
* input[] = {3, 6, 1, 9, 7, 8}
* output[] = {1, 6, 8, 9, 7, 3}
* */
public class TestNewSort {
public static void main(String args[]){
int input[] = {3, 6, 1, 9, 7, 8};
TestNewSort tn = new TestNewSort();
int output[] = tn.getNewSort(input);
for(int i=0; i< output.length; i++){
System.out.print(output[i] + " ");
}
}
public int[] getNewSort(int[] input){
int[] newArr = input;
for(int i=0; i<newArr.length; i++){
for(int j=0; j<newArr.length-1-i; j++){
if(newArr[j]<newArr[j+1]){
int temp = newArr[j];
newArr[j] = newArr[j+1];
newArr[j+1] = temp;
}
}
}
int[] temp = new int[newArr.length];
temp[newArr.length/2] = newArr[0];
int high = newArr.length/2 + 1;
int low = newArr.length/2 - 1;
for(int i=1; i<newArr.length; ){
if(low >=0){//依次将大的元素排在左边
temp[low] = newArr[i];
low--;
i++;
}
if(high<newArr.length){//依次将第二大的排在右边
temp[high] = newArr[i];
high++;
i++;
}
}
return temp;
}
}
- 华为上机练习题--按照新规则排序
- 华为上机练习题
- 华为上机练习题
- 华为上机练习题--计算表达式
- 华为上机练习题--按位取反操作
- 华为上机练习题--压缩字符串
- 华为上机练习题--约瑟夫环问题
- 华为上机练习题--大数字的运算
- 华为上机练习题--括号匹配检测
- 华为上机练习题--重复字符过滤
- 华为上机练习题--简单加减表达式计算
- 华为上机练习题--姓名夫妻相
- 【华为上机】一左一右排序问题
- 华为上机练习题--判断某数字是否是回文数字
- 华为上机练习题--统计各小写字符出现的次数
- 华为上机练习题--按身高找出最佳二人组
- 华为上机练习题--求两个数组的总和
- 华为上机练习题--将英文号码翻译成数字号码
- 华为上机练习题--求两个数组的总和
- 黑马程序员 Map集合
- 一个有意思的面试题
- xampp环境下drupal安装心得
- opencv中图像连续显示的内存泄露问题的解决办法
- 华为上机练习题--按照新规则排序
- POJ 4002 Alice's mooncake shop(DP,单调队列)
- hdu 4276 The Ghost Blows Light(树型DP)
- 内存分配器 (Memory Allocator)
- RR调度(Round-robin scheduling)简介
- 激活后台窗口
- LeetCode 42. Multiply Strings
- LeetCode 44. Permutations
- LeetCode 45. Permutations II