1095. Maximum Swap —— Weekly Challenge
Posted lizzyluvcoding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1095. Maximum Swap —— Weekly Challenge相关的知识,希望对你有一定的参考价值。
题目限定输入是[0, 10^8],因而不用考虑负数或者越界情况,算是减小了难度。
1 public class Solution { 2 /** 3 * @param num: a non-negative intege 4 * @return: the maximum valued number 5 */ 6 public int maximumSwap(int num) { 7 // Write your code here 8 char[] numArrays = String.valueOf(num).toCharArray(); 9 if (numArrays.length < 2) { 10 return num; 11 } 12 13 //第一个递增点: 14 int firstHeigerPoint = 0; 15 for (int i = 0; i < numArrays.length - 1; i++) { 16 if (numArrays[i] < numArrays[i + 1]) { 17 firstHeigerPoint = i + 1; 18 break; 19 } 20 } 21 22 if (firstHeigerPoint == 0) { 23 return num; 24 } 25 26 //找到递增点后的最大值(如有相等情况取低位,因而更新条件是numArrays[j] >= max) 27 int max = numArrays[firstHeigerPoint]; 28 int maxPoint = firstHeigerPoint; 29 for (int j = firstHeigerPoint; j < numArrays.length; j++) { 30 if (numArrays[j] >= max) { 31 max = numArrays[j]; 32 maxPoint = j; 33 } 34 } 35 36 //找到第一个更小的高位 37 int toSwapIndex = firstHeigerPoint-1; 38 for (int i = 0; i <= firstHeigerPoint - 1; i++) { 39 if (numArrays[i] < max) { 40 toSwapIndex = i; 41 break; 42 } 43 } 44 45 46 47 char temp = numArrays[toSwapIndex]; 48 numArrays[toSwapIndex] = numArrays[maxPoint]; 49 numArrays[maxPoint] = temp; 50 51 return Integer.parseInt(new String(numArrays)); 52 } 53 }
以上是关于1095. Maximum Swap —— Weekly Challenge的主要内容,如果未能解决你的问题,请参考以下文章