全不带等号的比较方式,如果 pivot 元素有唯一对应,可以 partition 并且 left == right 停留在 pivot 上;否则多个等于 pivot 时会死循环,因为不带等号无法让指针跨过 等于 pivot 的元素。
/** * public class NBCompare { * public int cmp(String a, String b); * } * You can use compare.cmp(a, b) to compare nuts "a" and bolts "b", * if "a" is bigger than "b", it will return 1, else if they are equal, * it will return 0, else if "a" is smaller than "b", it will return -1. * When "a" is not a nut or "b" is not a bolt, it will return 2, which is not valid.*/publicclassSolution { /** * @param nuts: an array of integers * @param bolts: an array of integers * @param compare: a instance of Comparator * @return: nothing */publicvoidsortNutsAndBolts(String[] nuts,String[] bolts,NBComparator compare) {// write your code herehelper(nuts, bolts, compare,0,nuts.length-1); }privatevoidhelper(String[] nuts,String[] bolts,NBComparator compare,int start,int end){if(start >= end) return;int pivot =partitionNuts(nuts, bolts[start], start, end, compare);partitionBolts(bolts, nuts[pivot], start, end, compare);helper(nuts, bolts, compare, start, pivot -1);helper(nuts, bolts, compare, pivot +1, end); }privateintpartitionNuts(String[] nuts,String bolt,int start,int end,NBComparator compare){int left = start;int right = end;while(left < right){while(left < right &&compare.cmp(nuts[left], bolt) <0) left ++;while(left < right &&compare.cmp(nuts[right], bolt) >0) right --;if(left < right) swap(nuts, left, right); }// 最终 left = right ,都停留在 pivot 上return left; }privateintpartitionBolts(String[] bolts,String nut,int start,int end,NBComparator compare){int left = start;int right = end;while(left < right){while(left < right &&compare.cmp(nut, bolts[left]) >0) left ++;while(left < right &&compare.cmp(nut, bolts[right]) <0) right --;if(left < right) swap(bolts, left, right); }return right; }privatevoidswap(String[] arr,int a,int b){String temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; }};
publicclassSolution { /** *@param chars: The letter array you should sort by Case *@return: void */publicvoidsortLetters(char[] chars) {//write your code hereint left =0;int right =chars.length-1;int cur =0;while(cur <= right){if(chars[cur] >='a'){swap(chars, cur ++, left ++); } elseif(chars[cur] <'a'){swap(chars, cur, right--); } else { cur ++; } } }privatevoidswap(char[] chars,int a,int b){char temp = chars[a]; chars[a] = chars[b]; chars[b] = temp;return; }}