670. Maximum Swap

Source: Internet
Author: User
670. Maximum Swap

Given a non-negative integer, you could swap two digits in most once to get the maximum number. Return the maximum valued number to could get.

Example 1:

input:2736 output:7236 Explanation:swap The number 2 and the number
7.

Example 2:

input:9973
output:9973
explanation:no swap.

Given a nonnegative number, swap the two digits in the number to get the maximum number.

Idea: See code comments

Code:

Package Array;



/**
* @Author oovever
* @Date 2017/11/28 10:10 * * Public
class Solution {public
  int maximumswap (int num) {
      char[] digits = string.valueof (num). ToCharArray ();
      int[] Buckets = new INT[10];
      for (int i=0;i<digits.length;i++) {
//            Find the last position of each number
          Buckets[digits[i]-' 0 ' = i;
      }
      for (int i=0;i<digits.length;i++) {
//            digits traverse buckets from back to current, find number greater than current digits[i] for
          (int j=9;j> digits[i]-' 0 '; j--) {
//                greater than digits[i] number must be greater than Digits[i index
              if (buckets[j) > i) {
                  char temp = Digits[i];
                  Digits[i] = digits[buckets[j]];
                  DIGITS[BUCKETS[J]] = temp;
                  Return integer.valueof (new String (digits));
      }} return num;
  }

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.