179. Largest Number
冒泡排序,每一轮都把最小的数字选出放在最后。
class Solution { public String largestNumber(int[] nums) { for(int i = 0; i < nums.length; i++){ for(int j = 0; j < nums.length - i - 1; j++){ String s1 = nums[j] + "" + nums[j + 1]; String s2 = nums[j + 1] + "" + nums[j]; if(s1.compareTo(s2) < 0){ int temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; } } } String res = ""; for(int i = 0; i < nums.length; i++){ res += nums[i]; } if(res.charAt(0) == '0'){ return "0"; } return res; } }
第二种,重写compare
public class Solution { public String largestNumber(int[] num) { if(num == null || num.length == 0) return ""; // Convert int array to String array, so we can sort later on String[] s_num = new String[num.length]; for(int i = 0; i < num.length; i++) s_num[i] = String.valueOf(num[i]); // Comparator to decide which string should come first in concatenation Comparator<String> comp = new Comparator<String>(){ @Override public int compare(String str1, String str2){ String s1 = str1 + str2; String s2 = str2 + str1; return s2.compareTo(s1); // reverse order here, so we can do append() later } }; Arrays.sort(s_num, comp); // An extreme edge case by lc, say you have only a bunch of 0 in your int array if(s_num[0].charAt(0) == '0') return "0"; StringBuilder sb = new StringBuilder(); for(String s: s_num) sb.append(s); return sb.toString(); } }
6. ZigZag Conversion
之字形走法,先用一个for添加从顶到底的char,第二个for添加斜向上的元素(不包括第一行sb[ 0 ],故用 i >= 1表示),依次类推。最后将所有sb [ i ] 依次添加到sb[ 0 ]的后面。记得 sb.toString( )。
class Solution { public String convert(String s, int numRows) { char[] c = s.toCharArray(); int len = c.length; StringBuilder[] sb = new StringBuilder[numRows]; for(int i = 0; i < numRows; i++){ sb[i] = new StringBuilder(); } int idx = 0; while(idx < len){ for(int i = 0; i < numRows && idx < len; i++){ sb[i].append(c[idx++]); } for(int i = numRows - 2; i >= 1 && idx < len; i--){ sb[i].append(c[idx++]); } } for(int i = 1; i < sb.length; i++){ sb[0].append(sb[i]); } return sb[0].toString(); } }
168. Excel Sheet Column Title
相当于转化为26进制。先减1 % 26取最小位。再减去余数继续除以26计算更高位。
class Solution { public String convertToTitle(int n) { StringBuilder sb = new StringBuilder(); int reminder = 0; while(n > 0){ reminder = (n - 1) % 26; sb.insert(0, (char)(reminder + 'A')); n = (n - reminder) / 26; } return sb.toString(); } }