package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * @ClassName: HeightChecker * @Author: xiaof * @Description: 1051. Height Checker * Students are asked to stand in non-decreasing order of heights for an annual photo. * Return the minimum number of students not standing in the right positions. * (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.) * Input: [1,1,4,2,1,3] * Output: 3 * Explanation: * Students with heights 4, 3 and the last 1 are not standing in the right positions. * @Date: 2019/7/3 9:19 * @Version: 1.0 */ public class HeightChecker { public int solution(int[] heights) { //首先排个序,然后比较一下就可以了!,来个快排吧 int[] array = new int[heights.length]; for(int i = 0; i < array.length; ++i) { array[i] = heights[i]; } quikSort1(array, 0, array.length); //比较不同的位置 int result = 0; for(int j = 0; j < array.length; ++j) { if(array[j] != heights[j]) { result++; } } return result; } private void quikSort1(int array[], int start, int end) { if(start < end) { int mid = this.hoarePartition(array, start, end); quikSort1(array, start, mid); quikSort1(array, mid + 1, end); } } private int hoarePartition(int[] array, int start, int end) { //对区间进行排序 int midValue = array[start]; int index1 = start, index2 = end; //为了避免自己重复比较 do { //左边查找比mid值大的 do { ++index1; } while(index1 < end && array[index1] < midValue); //找到比mid小的值 do { --index2; } while(index2 > start && array[index2] > midValue); //交换数据 if(index1 < index2) { int temp = array[index1]; array[index1] = array[index2]; array[index2] = temp; } } while(index1 < index2); //最后我们把坑填到中间位置,因为index1和index2错开位置了,我们交换回来 // int temp = array[index1]; // array[index1] = array[index2]; // array[index2] = temp; //填坑 array[start] = array[index2]; array[index2] = midValue; return index2; } public static void main(String args[]) { int A[] = {7,4,5,6,4,2,1,4,6,5,4,8,3,1,8,2,7,6,3,2}; int A1[] = {1,1,4,2,1,3}; int A2[] = {1,4,3,2}; HeightChecker fuc = new HeightChecker(); System.out.println(fuc.solution(A2)); } }