剑指Offer之Java算法习题精讲数组查找与字符串交集
题目一
数组题——二分查找法
写一个函数查找给定的数组中指定的数值
具体题目如下
解法
class Solution { public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while(left<=right){ int mid = left+(right-left)/2; if(nums[mid]==target){ return mid; }else if(nums[mid]>target){ right = mid - 1; }else if(nums[mid]<target){ left = mid + 1; } } return -1; } }
题目二
数组题——查找数组中元素位置
根据给定的数组按照指定条件查找首尾元素位置
具体题目如下
解法:
class Solution { public int[] searchRange(int[] nums, int target) { int[] res = {-1,-1}; int left = 0; int right = nums.length-1; while(left<=right){ int mid = left+(right-left)/2; if(nums[mid] == target){ res[0] = mid; right = mid-1; }else if(nums[mid]>target){ right = mid - 1; }else if(nums[mid]<target){ left = mid+1; } } left = 0; right = nums.length-1; while(left<=right){ int mid = left+(right-left)/2; if(nums[mid] == target){ res[1] = mid; left = mid+1; }else if(nums[mid]>target){ right = mid - 1; }else if(nums[mid]<target){ left = mid+1; } } return res; } }
题目三
字符串题——查找字符串交集
根据给定的字符串按照指定条件查找一个字符串所涵盖的另一个字符串字符的最小子串
具体题目如下
解法
class Solution { public String minWindow(String s, String t) { if(s == null || s == "" || t == null || t == "" || s.length() < t.length()){ return ""; } int[] need = new int[128]; int[] have = new int[128]; for (int i = 0; i < t.length(); i++) { need[t.charAt(i)]++; } int left = 0, right = 0; int min = s.length() + 1, count = 0, start = 0; while (right < s.length()){ char r = s.charAt(right); if (need[r] == 0) { right++; continue; } if (have[r] < need[r]) { count++; } have[r]++; right++; while (count == t.length()){ if (right - left < min) { min = right - left; start = left; } char l = s.charAt(left); if (need[l] == 0) { left++; continue; } if (have[l] == need[l]) { count--; } have[l]--; left++; } } if (min == s.length() + 1) { return ""; } return s.substring(start, start + min); } }
到此这篇关于剑指Offer之Java算法习题精讲数组查找与字符串交集的文章就介绍到这了,更多相关Java 数组查找内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)