164. Maximum Gap
用桶排序的方法做。注意两个具有最大间距的两个数肯定不在一个桶。
public class Solution {
public int maximumGap(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
int min = nums[0];
int max = nums[0];
for (int i:nums) {
min = Math.min(min, i);
max = Math.max(max, i);
}
int gap = (int)Math.ceil((double)(max - min)/(nums.length - 1));
int[] bmin = new int[nums.length - 1];
int[] bmax = new int[nums.length - 1];
Arrays.fill(bmin, Integer.MAX_VALUE);
Arrays.fill(bmax, Integer.MIN_VALUE);
for (int i:nums) {
if (i == min || i == max) {
continue;
}
int index = (i - min) / gap;
bmin[index] = Math.min(i, bmin[index]);
bmax[index] = Math.max(i, bmax[index]);
}
int maxgap = Integer.MIN_VALUE;
int previous = min;
for (int i = 0; i < nums.length - 1; i++) {
if (bmax[i] == Integer.MIN_VALUE && bmin[i] == Integer.MAX_VALUE) {
continue;
}
maxgap = Math.max(maxgap, bmin[i] - previous);
previous = bmax[i];
}
maxgap = Math.max(maxgap, max - previous);
return maxgap;
}
}
242. Valid Anagram
public class Solution {
public boolean isAnagram(String s, String t) {
if(s==null||t==null||s.length()!=t.length())
return false;
if (s.equals(t)) {
return true;
}
int[] charset = new int[26];
for (int i = 0; i < s.length(); i++) {
charset[s.charAt(i) - 'a']++;
charset[t.charAt(i) - 'a']--;
}
for (int i:charset) {
if (i != 0) {
return false;
}
}
return true;
}
}
179. Largest Number
这道题主要是修改比较器,直观的表示就是比较两个数谁当另外一个前缀得到的组合数比较大。
public class Solution {
public String largestNumber(int[] nums) {
if(nums == null || nums.length == 0)
return "";
String[] arr = new String[nums.length];
for(int i = 0; i < nums.length; i++)
arr[i] = String.valueOf(nums[i]);
Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
String ss1 = s1 + s2;
String ss2 = s2 + s1;
return ss2.compareTo(ss1);
}
});
if(arr[0].charAt(0) == '0')
return "0";
StringBuilder sbuilder = new StringBuilder();
for(String e : arr) {
sbuilder.append(e);
}
return sbuilder.toString();
}
}