1. 1-bit and 2-bit Characters

We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).

Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.

Example 1:

Input:
bits = [1, 0, 0]
Output: True
Explanation:
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. 

Example 2:

Input:
bits = [1, 1, 1, 0]
Output: False
Explanation:
The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.

Note:

  • 1 <= len(bits) <= 1000.
  • bits[i] is always 0 or 1.

解题思路:找规律,可能出现的数字只有三种组合 0,10,11。所以从左往右扫描输入数字串的时候,从头开始,如果第一位是0,那么断定只有1个bit,如果是1,则断定是2个bit,这样去掉已经判别好的继续往右边扫描(其实可以看成每次都从头扫描)判断即可。

import java.util.*;

public class LeetCode{
public static void main(String[] args){
Scanner sc=new Scanner(System.in); //将输入字符串转为int数组
String input=sc.nextLine();
int n=input.length();
int[] bits=new int[n];
for(int i=0; i<n; i++){
bits[i]=input.charAt(i)-'0';
} boolean result=isOneBitCharacter(bits);
System.out.println(result);
}
} public static boolean isOneBitCharacter(int[] bits){
int i=0; //这里i是数组下标,需要不断往后扫描
while(i<bits.length-1){
i=i+bits[i]+1;
}
return i==bits.length-1;
}
}

总结:这题是众多字符串找规律题目中的一个,找到规律即可,不需要利用什么贪心,动态规划等思路。

2. 132 Pattern

Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.

Note: n will be less than 15,000.

Example 1:

Input: [1, 2, 3, 4]

Output: False

Explanation: There is no 132 pattern in the sequence.

Example 2:

Input: [3, 1, 4, 2]

Output: True

Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

Input: [-1, 3, 2, 0]

Output: True

Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].

解题思路:可以使用遍历的方法,3层循环从左往右扫描,但是会超时。

方法一是改进的遍历法,对于ai,aj,ak。i<j<K,以中间的 j 开始遍历,对于aj,只要在左边找到一个小于它的ai,在右边找到小于 aj 但大于 ai 的 ak 即可,为了扩大 ak 的搜索范围,只需要和左边小于 aj 中的最小值比较即可,故当 aj 从左往右遍历时,需要记录其中小于 aj 的最小值。

import java.util.*;

public class LeetCode{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String input=sc.nextLine();

     // 这里用“|”来匹配多个替换,对于中括号,前面要加上转义字符 \\
String str=input.replaceAll(",| |\\]|\\[","");
char[] crs=str.toCharArray();
int[] nums=new int[crs.length];
for(int i=0; i<crs.length; i++){
nums[i]=crs[i]-'0';
}
System.out.println(find132pattern(nums));
} public static boolean find132pattern(int[] nums) {
int min_i = Integer.MAX_VALUE;
for (int j = 0; j < nums.length - 1; j++) {
min_i = Math.min(min_i, nums[j]);
for (int k = j + 1; k < nums.length; k++) {
if (nums[k] < nums[j] && min_i < nums[k])
return true;
}
}
return false;
} }

方法二是Serching intervals(不知道怎么翻译这个。。。),以例子 [5 6 4 7 3 8 2 9] 来说明思路,先转化为一张图:

其实还是从 ai,aj 入手来遍历寻找 ak,估计是 ak 好找(因为限定条件多),从上图来看,有上升的线和下降的线构成,对于每一对上升的线,起点 num[s] 和终点 nums[i-1] 自然构成了 ai 和 aj,而对于 nums[i] 则可能构成 ak,故从左往右扫描,记录遇到的上升线 [num[s],num[i-1]]。对于上升线的后一点 num[i] 开始遍历判断,这个遍历过程中同样要记录遇到的上升线,然后对上升线的后一点和之前所有的上升线对进行比较,如果是下降线的情况直接递增i遍历即可。

import java.util.*;

public class LeetCode{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine(); String str = input.replaceAll(",| |\\]|\\[","");
char[] crs = str.toCharArray(); int[] nums = new int[crs.length];
for(int i = 0; i < crs.length; i++){
nums[i] = crs[i]-'0';
}
System.out.println(find132pattern(nums));
} public static boolean find132pattern(int[] nums) {     //List< int[] a > intervals = new List<>(); 错误写法
List < int[] > intervals = new ArrayList < > ();
int i = 1, s = 0;
while (i < nums.length) {
if (nums[i] <= nums[i - 1]) {
if (s < i - 1)
intervals.add(new int[] {nums[s], nums[i - 1]});
s = i;
}
for (int[] a: intervals)
if (nums[i] > a[0] && nums[i] < a[1])
return true;
i++;
}
return false;
}
}

方法三是利用栈 (Stack),入手点还是通过 ai,aj 限定 ak 来考虑。有点复杂,较难叙述,还是直接看官方解释吧:https://leetcode.com/problems/132-pattern/solution/

import java.util.*;

public class LeetCode{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine(); String str = input.replaceAll(",| |\\]|\\[","");
char[] crs = str.toCharArray(); int[] nums = new int[crs.length];
for(int i = 0; i < crs.length; i++){
nums[i] = crs[i]-'0';
}
System.out.println(find132pattern(nums));
} public static boolean find132Pattern(int[] nums){
if (nums.length < 3)
return false;
Stack < Integer > stack = new Stack < > ();
int[] min = new int[nums.length];
min[0] = nums[0];
for (int i = 1; i < nums.length; i++)
min[i] = Math.min(min[i - 1], nums[i]);
for (int j = nums.length - 1; j >= 0; j--) {
if (nums[j] > min[j]) {
while (!stack.isEmpty() && stack.peek() <= min[j])
stack.pop();
if (!stack.isEmpty() && stack.peek() < nums[j])
return true;
stack.push(nums[j]);
}
}
return false;
}
}

3. 3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

解题思路:虽然可以用遍历的方法来穷举所有可能的三元组,但是时间复杂度会达到O(n3),肯定会超时的。一个可行的方式是,先将数组由小到大排序一遍,从第一个数字开始遍历,将其作为基准,剩下的两个数和与其相反数相同即可。因为整个数组是排号序的,所以可以借鉴快排的思想来使寻找剩下两个数的时间复杂度达到O(n),这样整个算法下来时间复杂度便是O(n2)。具体做法是这样,从基准数字的后一个数字和数组的最后一个数字开始索引,如果其和小于基准数字则将左边索引加1,如果大于则将右边索引减1往左移即可,如果等于基准数字的相反数则即是我们要找的数字对,此时要将左右索引各向右左移动一位,如果和之前的索引数字相等还要继续左/右移索引(为了去重),因为左边增大右边缩小这样剩下的数字中还有可能和基准数字构成 3Sum 数字对。在寻找完与基准数字所有相对应的 3Sum 数字对后,将基准数字后移一位重复此步骤。左右两边这样移动到最后直至左索引大于右索引时还不等于基准数字的相反数则表明基准数字不出现在 3Sum 数字对中,后移基准数字继续寻找。还要一点要注意的是因为题目中说了不能出现重复的数字对,所以在后移基准数字时要和前一个基准数字比较,如果相等则直接右移基准数字。

import java.util.*;

public class LeetCode{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String input=sc.nextLine(); //首先将输入的字符串转为int数组,这里有正负号,所以还是先变为字符串数组再转为int数组
String str=input.replaceAll(" |\\]|\\[","");
String[] strs=str.split(",");
int[] nums=new int[strs.length];
for(int i=0;i<strs.length;i++){
nums[i]=Integer.parseInt(strs[i]);
} for(List<Integer> pair: find3Sum(nums)){
for(int i : pair){
System.out.print(i+" ");
}
System.out.println();
}
} public static List<List<Integer>> find3Sum(int[] num){
    // 利用 Arrays 自带的排序方法
Arrays.sort(num);
List<List<Integer>> res = new LinkedList<>();
for (int i = 0; i < num.length-2; i++) {
if (i == 0 || (i > 0 && num[i] != num[i-1])) {
int lo = i+1, hi = num.length-1, sum = 0 - num[i];
while (lo < hi) {
if (num[lo] + num[hi] == sum) {
              //这里直接用 Arrays.asList 方法直接将数字对转为List集合
res.add(Arrays.asList(num[i], num[lo], num[hi]));
while (lo < hi && num[lo] == num[lo+1]) lo++;
while (lo < hi && num[hi] == num[hi-1]) hi--;
lo++; hi--;
} else if (num[lo] + num[hi] < sum) lo++;
else hi--;
}
}
}
return res;
}
}

LeetCode解题报告—— 1-bit and 2-bit Characters & 132 Pattern & 3Sum的更多相关文章

  1. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  2. leetcode解题报告(2):Remove Duplicates from Sorted ArrayII

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  3. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  4. leetCode解题报告5道题(六)

    题目一: Longest Substring Without Repeating Characters Given a string, find the length of the longest s ...

  5. LeetCode解题报告—— Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  6. LeetCode解题报告—— Search in Rotated Sorted Array & Search for a Range & Valid Sudoku

    1. Search in Rotated Sorted Array Suppose an array sorted in ascending order is rotated(轮流,循环) at so ...

  7. LeetCode解题报告—— 2 Keys Keyboard & Longest Palindromic Substring & ZigZag Conversion

    1. Longest Palindromic Substring Given a string s, find the longest palindromic substring in s. You ...

  8. LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结

    前言: 这几天在做LeetCode 里面有2sum, 3sum(closest), 4sum等问题, 这类问题是典型的递归思路解题.该这类问题的关键在于,在进行求和求解前,要先排序Arrays.sor ...

  9. leetcode解题报告(13):K-diff Pairs in an Array

    描述 Given an array of integers and an integer k, you need to find the number of unique k-diff pairs i ...

随机推荐

  1. 牛客网 Wannafly挑战赛27 蓝魔法师

    蓝魔法师 链接: https://www.nowcoder.com/acm/contest/215/C 来源:牛客网 题目描述 "你,你认错人了.我真的,真的不是食人魔."--蓝魔 ...

  2. 在Linux中新增与删除用户可以使用命令:Useradd

    在Linux中新增与删除用户可以使用命令:Useradd 我们先使用man命令理解一下Useradd的用法 新增与删除用户操作需要先获取高级用户权限 输入命令:sudo -i 确定后输入高级用户密码 ...

  3. Codeforces Round #401 (Div. 2) A B C 水 贪心 dp

    A. Shell Game time limit per test 0.5 seconds memory limit per test 256 megabytes input standard inp ...

  4. CCPC-Winter Camp div2 day5

    DIV2 有部分div1的题会写 div1的大佬真的太强了 向他们学习 (好像和zqc大佬说过话了hhh,zqc大佬真的是一个超有意思的人啊,羡慕有妹子队友的zqc大佬) A: 你有一棵树,你想把它画 ...

  5. boost文件锁的使用

    boost中可以用boost::interprocess::file_lock类对文件进行加锁和解锁操作. #include <fstream> #include <iostream ...

  6. zoj 2369 Two Cylinders

    zoj 2369 Two Cylinders 链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2369 题意:已知两个无 ...

  7. 【Android】完善Android学习(三:API 3.0)

    备注:之前Android入门学习的书籍使用的是杨丰盛的<Android应用开发揭秘>,这本书是基于Android 2.2API的,目前Android已经到4.4了,更新了很多的API,也增 ...

  8. linux时区修定转

    https://blog.csdn.net/feng12345zi/article/details/80348501

  9. 超详细的Java面试题总结(二)之Java基础知识篇

    多线程和Java虚拟机 创建线程有几种不同的方式?你喜欢哪一种?为什么? 继承Thread类 实现Runnable接口 应用程序可以使用Executor框架来创建线程池 实现Callable接口. 我 ...

  10. 【tomcat】手动部署动态JavaWeb项目到tomcat

    1.通过修改server.xml进行配置 1.查看项目的目录结构: tomcat运行时加载WebConmtent目录