Tuesday, March 8, 2022

Leetcode discuss: 670. Maximum Swap

March 8, 2022

Here is the link. 

C# | Sort a char array | case study: 1993

March 7, 2022
Introduction
The idea is to sort the integer as a char array, and then compare leftmost digit to largest digit, and then find first one unequal.

Case study: 1993 | Answer should be 9913, not 9193
I should choose to compare from rightmost digit first to find the swap digit based on failed test case: 9913.

The following C# code passes online judge.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _670_maximum_swap
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = MaximumSwap(1993);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static int MaximumSwap(int num) {
            var unsorted = num.ToString().ToCharArray();
            var length = unsorted.Length;
            var sorted = new char[length];
            Array.Copy(unsorted, sorted, length);

            Array.Sort(sorted);            

            for (int i = 0; i < length; i++)
            {
                if (unsorted[i] - '0' < sorted[length - 1 - i] - '0')
                {
                    var digit1 = unsorted[i] - '0';
                    var digit2 = sorted[length - 1 - i] - '0';

                    // swap those two digits
                    for (int j = length - 1; j >= i + 1; j--)
                    {
                        if (unsorted[j] - '0' == digit2)
                        {
                            unsorted[i] = unsorted[j];
                            unsorted[j] = (char)(digit1 + '0');

                            return Convert.ToInt32(new string(unsorted));
                        }                        
                    }
                }                
            }

            return num;
        }
    }
}


No comments:

Post a Comment