本文隶属于专栏《LeetCode 刷题汇总》,该专栏为笔者原创,引用请注明来源,不足和错误之处请在评论区帮忙指出,谢谢!
本专栏目录结构请见LeetCode 刷题汇总
幕布链接
官方题解
class Solution { public int maxArea(int[] height) { int maxArea = 0; int low = 0, high = height.length - 1; while (low < high) { maxArea = Math.max(maxArea, Math.min(height[low], height[high]) * (high - low)); if (height[low] > height[high]) { high--; } else { low++; } } return maxArea; } }
class Solution { public int maxArea(int[] height) { int n = height.length, left = 0, right = n - 1, leftMax = 0, rightMax = 0, max = 0; while(left < right){ leftMax = Math.max(leftMax, height[left]); rightMax = Math.max(rightMax, height[right]); max = Math.max(max, Math.min(height[left], height[right]) * (right - left)); if(leftMax >= rightMax){ right--; }else{ left++; } } return max; } }
My java solution easy to understand
class Solution { public String intToRoman(int num) { int[] nums = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; String[] romans = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; StringBuilder res = new StringBuilder(); int index = 0; while(index < 13){ while(num >= nums[index]){ res.append(romans[index]); num -= nums[index]; } index++; } return res.toString(); } }
Clean O(n) c++ solution
class Solution { Map<Character, Integer> symbolValues = new HashMap<>() {{ put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000); }}; public int romanToInt(String s) { int ans = 0; int n = s.length(); for (int i = 0; i < n; ++i) { int value = symbolValues.get(s.charAt(i)); if (i < n - 1 && value < symbolValues.get(s.charAt(i + 1))) { ans -= value; } else { ans += value; } } return ans; } }
Java code with 13 lines
class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } int length = strs[0].length(); int count = strs.length; for (int i = 0; i < length; i++) { char c = strs[0].charAt(i); for (int j = 1; j < count; j++) { if (i == strs[j].length() || strs[j].charAt(i) != c) { return strs[0].substring(0, i); } } } return strs[0]; } }
Concise O(N^2) Java solution
class Solution { public List<List<Integer>> threeSum(int[] nums) { int n = nums.length; if(n < 3){ return new ArrayList<>(0); } Arrays.sort(nums); List<List<Integer>> res = new ArrayList<>(); for(int i = 0; i < n - 2; i++){ if(i > 0 && nums[i] == nums[i - 1]){ continue; } int a = nums[i], j = i + 1, k = n - 1; while(j < k){ if(nums[j] + nums[k] + a == 0){ res.add(Arrays.asList(a, nums[j], nums[k])); while(j < k && nums[j] == nums[j + 1]){ j++; } j++; while(j < k && nums[k] == nums[k - 1]){ k--; } k--; }else if(nums[j] + nums[k] + a < 0){ j++; }else{ k--; } } } return res; } }