C# accepted, 190ms, custom comparer of strings + bubble sort


  • 0
    R
    public class Solution {
        
            public string LargestNumber(int[] nums)
            {
                string[] strs = new string[nums.Length];
                for (int k = 0; k < nums.Length; k++)
                {
                    strs[k] = nums[k].ToString();
                }
    
                for (int i = 0; i < strs.Length - 1; i++)
                {
                    bool isOK = true;
                    for (int j = 0; j < strs.Length - 1; j++)
                    {
                        if (Compare(strs[j], strs[j + 1]) == -1)
                        {
                            isOK = false;
                            string temp = strs[j];
                            strs[j] = strs[j + 1];
                            strs[j + 1] = temp;
                        }
                    }
    
                    if (isOK)
                    {
                        break;
                    }
                }
    
                string result = "";
                for (int p = 0; p < strs.Length; p++)
                {
                    result += strs[p];
                }
                while (result[0] == '0' && result.Length > 1)
                {
                    result = result.Substring(1);
                }
                return result;
            }
            
            public static int Compare(string a, string b)
            {
                if (a.Length == b.Length)
                {
                    for (int j = 0; j < a.Length; j++)
                    {
                        if (a[j] > b[j])
                        {
                            return 1;
                        }
                        if (a[j] < b[j])
                        {
                            return -1;
                        }
                    }
                    return 0;
                }
                
                int minLength = Math.Min(a.Length, b.Length);
                int i = 0;
                for (; i < minLength; i++)
                {
                    if (a[i] > b[i])
                    {
                        return 1;
                    }
                    if (a[i] < b[i])
                    {
                        return -1;
                    }
                }
    
                if (a.Length < b.Length)
                {
                    string tempB = b.Substring(i);
                    return (Compare(a, tempB));
                }
    
                if (b.Length < a.Length)
                {
                    string tempA = a.Substring(i);
                    return (Compare(tempA, b));
                }
    
                return a.Length < b.Length ? 1 : -1;
            }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.