码迷,mamicode.com
首页 > 其他好文 > 详细

1095. Maximum Swap —— Weekly Challenge

时间:2018-12-05 21:46:24      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:hal   index   isp   nbsp   bre   challenge   ret   val   负数   

题目限定输入是[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 }
View Code

 

1095. Maximum Swap —— Weekly Challenge

标签:hal   index   isp   nbsp   bre   challenge   ret   val   负数   

原文地址:https://www.cnblogs.com/lizzyluvcoding/p/10073422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!