1. 盛最多水的容器(11)
给定一个长度为 n
的整数数组 height
。有 n
条垂线,第 i
条线的两个端点是 (i, 0)
和 (i, height[i])
思想:双指针
class Solution { public int maxArea(int[] height) { int left = 0; int right = height.length-1; int max =0; while (left<right){ int h = Math.min(height[left],height[right]); int w = right-left; max = max< h*w ? h*w:max; if(height[left]<height[right]){ left++; }else { right--; } } return max; } }
2. 整数转罗马数字(12)
class Solution { int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; public String intToRoman(int num) { StringBuffer res = new StringBuffer(); for (int i = 0; i < values.length; i++) { int value = values[i]; String symbol = symbols[i]; while (num >= value) { num -= value; res.append(symbol); } if (num == 0) { break; } } return res.toString(); } }
3. 罗马数字转整数(13)
class Solution { private int getValue(char ch) { switch(ch) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } } public int romanToInt(String s) { int sum =0; int prenum = getValue(s.charAt(0)); for (int i = 1; i <s.length() ; i++) { int num = getValue(s.charAt(i)); if (prenum>=num){ sum+=prenum; }else { sum-=prenum; } prenum=num; } sum+=prenum; return sum; } }
4.最长公共前缀(14)
class Solution { public String longestCommonPrefix(String[] strs) { if (strs==null||strs.length==0) return ""; int minlen =Integer.MAX_VALUE; for (int i = 0; i <strs.length ; i++) { minlen = Math.min(strs[i].length(),minlen); } int low = 0; int high = minlen; while (low<high){ int mid = (high-low+1)/2+low; if(getPrefix(strs,mid)){ low=mid;} else {high=mid-1;} } return strs[0].substring(0,low); } private boolean getPrefix(String[] strs, int length) { String str0 = strs[0].substring(0, length); int count = strs.length; for (int i = 1; i < count; i++) { String str = strs[i]; for (int j = 0; j < length; j++) { if (str0.charAt(j) != str.charAt(j)) { return false; } } } return true; } }
标签:case,return,String,int,sum,num,打卡,922 From: https://www.cnblogs.com/forever-fate/p/17723549.html