(百度)经典排序算法不能忘呀,虽然复杂度有点高(大牛请回避)

度爸爸回家
import java.util.Scanner;
import java.util.*;
/**
 * 我没用集合啊哈哈,数组-容器换来换去换来换去换来换去
 * @author ddw
 *
 */
public class Main2 {
    public static void main(String[] args) {
    	int N;
    	int max,tmp,pos;
    	int countpath = 0;
    	int[] path = {};
    	List<Integer> path2 = new ArrayList<Integer>();
        Scanner in = new Scanner(System.in);
        N = in.nextInt();
        if(N > 50) {
        	System.out.println("Intput Error");
        }
        for(int i = 0; i < N; i++) {
        	path[i] = in.nextInt();
        }
        for(int j = N - 1; j >= 0; j++) {//选排
        	for(int k = 0; k < path.length; k++) {
        		max = path[k];
        		pos = k;
        		if(max < path[pos+1]) {
        			tmp = max;
        			max = path[pos+1];
        			path[pos+1] = tmp;
        		}
        	}
        }
        for(int i = 0; i < path.length; i++) {
        	path2.add(path[i]);
        }
        path2.remove(path2.get(path2.size()));
        for(int i = 0; i < path2.size(); i++) {
        	int startpos = path2.get(i);
        	countpath += Math.abs(startpos - countpath);
        }
        System.out.println(countpath);
    }
}



度爸爸买帽子
import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		int N,j=0;
		int D,v,token;//D为增量序列
		int[] price = {};
		Scanner in = new Scanner(System.in);
		N = in.nextInt();
		if(N > 50) {
			System.out.println("Input OutOfRange!");
			return;
		}
		System.out.println(N);
		for(int i = 0; i < N; i++) {
			price[j++] = in.nextInt();
			if(price[j] < 0 || price[j] > 1000) {
				System.out.println("NumberFromatError!");
				return;
			}
		}
		D = price.length / 2;
		for(int p = D; p < price.length; p /= 2) {//希尔排序
			for(int k = p; k < price.length; k += p) {
				v = price[k];
				token = k;
				while(price[token-p] > price[token] && token >= p) {
					price[token] = price[token - p];
					token = token - p;
				}
				price[token] = v;
			}
		}
		
		for(int i = 0; i < price.length; i++) {//当数字种类达到3时结束循环
			int kind = 0;
			int postion = 0;
			if(kind == 3) {
				System.out.println(price[postion]);
				return;
			}
			if(postion + 1 < price.length&& price[postion] != price[postion + 1]) {
				kind++;
				postion++;
			}
			else {
				postion++;
			}
		}
		System.out.println(-1);
		

	}

}


全部评论
一脸懵逼😰
点赞 回复 分享
发布于 2017-06-13 16:57

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务