Java 数组
明天一定. 人气:0题目一
解法
class Solution { public int findLengthOfLCIS(int[] nums) { if(nums.length==1) return 1; int fast = 1; int tmp = 1; int max = Integer.MIN_VALUE; while(fast<nums.length){ if(nums[fast]>nums[fast-1]){ tmp++; max = Math.max(max,tmp); }else{ max = Math.max(max,tmp); tmp = 1; } fast++; } return max; } }
题目二
解法
class Solution { public boolean validPalindrome(String s) { int left = 0; int right = s.length()-1; while(left<right){ if(s.charAt(left)==s.charAt(right)){ left++; right--; }else{ String tmp = s.substring(left, right + 1); return validPalindrome(tmp,1,tmp.length()-1)||validPalindrome(tmp,0,tmp.length()-2); } } return true; } public boolean validPalindrome(String s, int low, int high) { for (int i = low, j = high; i < j; ++i, --j) { char c1 = s.charAt(i), c2 = s.charAt(j); if (c1 != c2) { return false; } } return true; } }
题目三
解法
class Solution { public double findMaxAverage(int[] nums, int k) { int w = nums.length-k; int max = Integer.MIN_VALUE; for(int i = 0;i<=w;i++){ int res = 0; for(int j = 0;j<k;j++){ res = nums[i+j]+res; } max = Math.max(max,res); } double ans = (double)max/k; return ans; } }
题目四
解法
class Solution { public int findShortestSubArray(int[] nums) { int[] n = new int[50001]; for(int i = 0;i<nums.length;i++){ n[nums[i]]+=1; } int max = Integer.MIN_VALUE; ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = 0;i<n.length;i++){ max = Math.max(n[i],max); } for(int i = 0;i<n.length;i++){ if(n[i]==max){ list.add(i); } } int min = Integer.MAX_VALUE; for(int i = 0;i<list.size();i++){ int res = list.get(i); int left = 0; int right = nums.length-1; while(nums[left]!=res){ left++; } while(nums[right]!=res){ right--; } min = Math.min(min,right-left+1); } return min; } }
加载全部内容