这是一个我面试某公司的算法题目:对一个字符数组进行排序,根据给定的字符,大于它的,放在数组的左边,小于它的,放在数组的右边,且数组中的元素之间的相对位置要保持不变。...
生活随笔
收集整理的這篇文章主要介紹了
这是一个我面试某公司的算法题目:对一个字符数组进行排序,根据给定的字符,大于它的,放在数组的左边,小于它的,放在数组的右边,且数组中的元素之间的相对位置要保持不变。...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這個題目面試的時候,用的是最簡單,但多開辟內存的方法,后來自己想想,在原數組進行操作的方法:
private static string GreaterLeftLessRight(string str, char c){char[] array = str.ToCharArray();int comparingIndex = str.IndexOf(c);int i = 0;int j = comparingIndex + 1;int lastExchangePositionInLeft = -1;int lastExchangePositionInRight = -1;int rightestIndex = comparingIndex;char tmp;while (i < comparingIndex || j < array.Length){int shouldExchangeInLeft = -1;int shouldExchangeInRight = -1;while (i < comparingIndex){if (array[i] < c){shouldExchangeInLeft = i;i++;break;}else{i++;}}while (j < array.Length){if (array[j] >= c){shouldExchangeInRight = j;j++;break;}else{j++;}}if (shouldExchangeInLeft != -1 && shouldExchangeInRight != -1 && array[shouldExchangeInRight] != c){ExchangeCharacterInArray(array, shouldExchangeInLeft, shouldExchangeInRight);lastExchangePositionInLeft = shouldExchangeInLeft;lastExchangePositionInRight = shouldExchangeInRight;}else if (shouldExchangeInLeft != -1 && shouldExchangeInRight == -1){tmp = array[shouldExchangeInLeft];int moveEndIndex = lastExchangePositionInRight == -1 ? array.Length - 1 : lastExchangePositionInRight;MoveCharacterInArray(array, shouldExchangeInLeft, moveEndIndex, tmp);i--;comparingIndex--;}else if (shouldExchangeInLeft != -1 && array[shouldExchangeInRight] == c){array[shouldExchangeInRight] = array[shouldExchangeInLeft];MoveCharacterInArray(array, shouldExchangeInLeft, rightestIndex, c);i--;comparingIndex--;}else if (shouldExchangeInLeft == -1 && shouldExchangeInRight != -1 && array[shouldExchangeInRight] != c){tmp = array[shouldExchangeInRight];MoveCharacterInArray(array, shouldExchangeInRight, comparingIndex, tmp);comparingIndex++;rightestIndex = comparingIndex;}else if (shouldExchangeInLeft == -1 && shouldExchangeInRight != -1 && array[shouldExchangeInRight] == c){int moveEndIndex = rightestIndex + 1;MoveCharacterInArray(array, shouldExchangeInRight, moveEndIndex, c);rightestIndex = moveEndIndex;}}return new string(array);}private static void MoveCharacterInArray(char[] array, int startIndex, int endIndex, char endCharacter){if (startIndex == endIndex){return;}else if (startIndex < endIndex){for (int k = startIndex; k < endIndex; k++){array[k] = array[k + 1];}array[endIndex] = endCharacter;}else{for (int k = startIndex; k > endIndex; k--){array[k] = array[k - 1];}array[endIndex] = endCharacter;}}private static void ExchangeCharacterInArray(char[] array, int leftPosition, int rightPosition){char tmp = array[leftPosition];array[leftPosition] = array[rightPosition];array[rightPosition] = tmp;}?
轉載于:https://www.cnblogs.com/lgc19/archive/2013/01/24/2874624.html
總結
以上是生活随笔為你收集整理的这是一个我面试某公司的算法题目:对一个字符数组进行排序,根据给定的字符,大于它的,放在数组的左边,小于它的,放在数组的右边,且数组中的元素之间的相对位置要保持不变。...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 测试用例设计--判定表
- 下一篇: [转载]ubuntu 12.10 软件源