本文主要是介绍第 215 场周赛,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
第 215 场周赛
- 设计有序流
- 确定两个字符串是否接近
- 将 x 减到 0 的最小操作数
设计有序流
class OrderedStream { List<String> res = new ArrayList<String>();String[] strs;int cur = 0;public OrderedStream(int n) {for(int i=0;i<n;i++) {res.add("");}res = new ArrayList<String>();strs = new String[n];cur = 1;}public List<String> insert(int id, String value) {strs[id-1] = value;List<String> curRes = new ArrayList<String>();if(id==cur) {for(int i=cur-1;i<strs.length;i++) {if(strs[i]==""|| strs[i]==null) {break;}res.add(strs[i]);curRes.add(strs[i]);cur++;// System.out.println("cur="+cur);}}return curRes;}
}/*** Your OrderedStream object will be instantiated and called as such:* OrderedStream obj = new OrderedStream(n);* List<String> param_1 = obj.insert(id,value);*/
确定两个字符串是否接近
class Solution {public boolean closeStrings(String word1, String word2) {int len1 = word1.length();int len2 = word2.length();if(len1!=len2) {return false;}Set<Character> set1 = new HashSet<Character>();Set<Integer> num1 = new HashSet<Integer>();int[] count1 = new int[26];for(int i=0;i<len1;i++) {count1[word1.charAt(i)-'a']++;set1.add(word1.charAt(i));}for(int i=0;i<26;i++) {if(count1[i]!=0) {num1.add(count1[i]);}}int[] count2 = new int[26];Set<Character> set2 = new HashSet<Character>();Set<Integer> num2 = new HashSet<Integer>();for(int i=0;i<len2;i++) {count2[word2.charAt(i)-'a']++;set2.add(word2.charAt(i));}for(int i=0;i<26;i++) {if(count2[i]!=0) {num2.add(count2[i]);}}Set<Character> set = new HashSet<Character>();set.addAll(set2);set.addAll(set1);if(set1.size()!=set2.size() || set.size()!=set2.size()) {return false;}Set<Integer> num = new HashSet<Integer>();num.addAll(num2);num.addAll(num1);
// System.out.println(num1.size()+" "+num2.size());if(num1.size()!=num2.size() || num.size()!=num1.size()) {return false;}return true;}
}
将 x 减到 0 的最小操作数
两边最小取中间最大
【转载】: https://leetcode-cn.com/problems/minimum-operations-to-reduce-x-to-zero/solution/shi-yong-hua-dong-chuang-kou-zhao-zhong-jian-zui-c/
class Solution {public int minOperations(int[] nums, int x) {// 使用滑动窗口找中间最长的片段使得sum(片段)=sum(nums)-xint maxPart = -1;int sum = Arrays.stream(nums).sum();int currentSum = 0;int left = 0;int right = 0;while (left < nums.length) {// 如果右边未到尽头,不断先向右探测片段,如果大于目标sum-x则左边移动直到结束if (right < nums.length) {currentSum += nums[right++];}while (currentSum > sum - x && left < nums.length) {currentSum -= nums[left++];}if (currentSum == sum - x) {maxPart = Math.max(maxPart, right - left);}if (right == nums.length) {left++;}}return maxPart == -1 ? -1 : nums.length - maxPart;}}
这篇关于第 215 场周赛的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!