剑指Offer之Java算法习题精讲数组与字符串
作者:明天一定.
跟着思路走,之后从简单题入手,反复去看,做过之后可能会忘记,之后再做一次,记不住就反复做,反复寻求思路和规律,慢慢积累就会发现质的变化
题目一
解法
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; } }
到此这篇关于剑指Offer之Java算法习题精讲数组与字符串的文章就介绍到这了,更多相关Java 数组内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!