0%

Greedy Array And String LEETCODE-100-DAY6

位运算及贪心思想(局部最优)。

125. Valid Palindrome(Palindrome)

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

1
2
Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

1
2
Input: "race a car"
Output: false

Constraints:

  • s consists only of printable ASCII characters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) return true;
int left = 0;
int right = s.length() - 1;
//判断里面是否为数字或者字母
while (left < right) {
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
left++;
}
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
right--;
}
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
}

260. Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

Example:

1
2
Input:  [1,2,1,3,2,5]
Output: [3,5]

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//位运算
// A B :二进制数字有且至少有一位是不同的
class Solution {
public int[] singleNumber(int[] nums) {
int diff = 0;
for (int num : nums) {
diff ^= num;//出现两次,相同为0,不同为1 3^5 =(110) -6,负数是用二进制的补码形式来表示,
}
diff &= -diff;//把不同的位取出来(负数是二进制的补码)
int[] res = new int[2];
for (int num : nums) {
if ((num & diff) == 0) {
res[0] ^= num;
} else {
res[1] ^= num;XWXW
}
}
return res;
}
}

32. Longest Valid Parentheses(Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

1
2
3
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

1
2
3
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int res = 0;
int start = -1;//把左括号的起点放入Stack中,把index=0的括号前面的位置记录一下,可以把0位也包含进去
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
if (stack.isEmpty()) {
start = i;//左括号就记录起点位置,右括号开头就把i给Start
} else {
stack.pop();//不需要记录pop出来的位置,因为是求最长的substring,知道起始位置就行
if (stack.isEmpty()) {
//前面的已经pop出来了()()
res = Math.max(res, i - start);//start存的是有效值的前一位,有效数组遍历是从0开始的,所以不用进行加一的操作
} else {
//case:(()),pop出来了,但是stack还有一个前面的(,匹配到内部()是合法的
res = Math.max(res, i - stack.peek());//stack中有一个以上个的值(括号的index), 把当前括号和紧随的左括号pick出来
}
}
}
}
return res;
}
}

22. Generate Parentheses(Parentheses)

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

1
2
3
4
5
6
7
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//时间复杂度4^n / 根号n 
//backtracking方法
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
if (n == 0) return res;
helper(res, "", n, n);//左括号和右括号都有n个,为空是因为string里面一开始什么都没有
return res;
}
public void helper(List<String> res, String s, int left, int right) {
if (left > right) {//开头是)()(是不合法的
return;//())不合法
}
if (left == 0 && right == 0) {
res.add(s);
return;
}
if (left > 0) {
helper(res, s + "(", left - 1, right);
}
if (right > 0) {
helper(res, s + ")", left, right - 1);
}
}
}

137. Single Number II

Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

1
2
Input: [2,2,3,2]
Output: 3

Example 2:

1
2
Input: [0,1,0,1,0,1,99]
Output: 99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* @lc app=leetcode.cn id=137 lang=java
*
* [137] 只出现一次的数字 II
*
* 0-> 1 ->2-> 0 出现第一和第二次的时候记录一下,
* 00 ->01 ->10 ->00从 0 1 2 3(3置换为0)
* 00 ->10 ->01 ->00从 0 1 2 3(3置换为0)将上面的01和10转换了位置(这是一种做题的思路)
*
* ones twos
* 0 0
* 0->1 0->0
* 1->0 0->1
* 0->0 1->0
*/

// @lc code=start
//如果只有一个数就是从0到1的过程
/*
* 1,讲结果存入Ones里(如果只有一个数,就直接存入Ones,并返回)
* 2,清空Ones,存入twos
* 3,清空twos
*/
class Solution {
//出现3次后,% 3 = 0,所以在出现第三次时,将其置为0
public int singleNumber(int[] nums) {
int ones = 0, twos = 0;
for (int i = 0; i < nums.length; i++) {
ones = (ones ^ nums[i]) & ~twos;//~为取反符号
twos = (twos ^ nums[i]) & ~ones;
}
return ones;
}
}
// @lc code=end

// class Solution {
// public int singleNumber(int[] nums) {
// HashMap<Integer, Integer> hashmap = new HashMap<>();
// for (int num : nums)
// hashmap.put(num, hashmap.getOrDefault(num, 0) + 1);
// //当Map集合中有这个key时,就使用这个key值,如果没有就使用默认值defaultValue
// for (int k : hashmap.keySet())
// if (hashmap.get(k) == 1) return k;
// return -1;
// }
// }

55. Jump Game(基础)

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Example 1:

1
2
3
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

1
2
3
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

Constraints:

  • 1 <= nums.length <= 3 * 10^4
  • 0 <= nums[i][j] <= 10^5
1
2
3
4
5
6
7
8
9
10
11
12
13
//greedy 贪心思想
//max代表当前能跳的最大步数
class Solution {
public boolean canJump(int[] nums) {
int max = 0;//max代表当前能跳的最大步数

for (int i = 0; i < nums.length; i++) {
if (i > max) return false;
max = Math.max(nums[i] + i, max);
}
return true;
}
}

135. Candy(基础)

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

Example 1:

1
2
3
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

1
2
3
4
Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
* @lc app=leetcode.cn id=135 lang=java
*
* [135] 分发糖果
*/

// @lc code=start
//贪心
// 从左到右遍历,使得右边评分更高的元素比左边至少多于1个糖果
// 从右到左遍历,使得左边评分更高的元素比右边至少多于1个糖果
import java.util.*;
class Solution {
public int candy(int[] ratings) {
if (ratings.length == 0) return 0;
//[4, 5, 1]从左到友,多给右面一个,然后从右到左,可能已经比左面大了,所以不需要给
int[] candies = new int[ratings.length];
Arrays.fill(candies, 1);

for (int i = 1; i < candies.length; i++) {
// -1是倒数第一个元素,每次要前跟后比
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
// -1是倒数第一个元素,每次要前跟后比
for (int i = candies.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
int res = 0;
for (int candy : candies) {
res += candy;
}
return res;
}
}
// @lc code=end

121. Best Time to Buy and Sell Stock(实现题)

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

1
2
3
4
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

1
2
3
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
* @lc app=leetcode.cn id=121 lang=java
*
* [121] 买卖股票的最佳时机
*/

// @lc code=start
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) return 0;
int min = prices[0];
int profit = 0;
for (int price :prices) {
min = Math.min(min, price);
profit = Math.max(profit, price - min);
}
return profit;
}
}
// [7,1,5,3,6,4]
// Answer 7 Expected Answer 5

// @lc code=end

122. Best Time to Buy and Sell Stock II(实现题)

Say you have an array prices for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

1
2
3
4
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

1
2
3
4
5
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

1
2
3
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Constraints:

  • 1 <= prices.length <= 3 * 10 ^ 4
  • 0 <= prices[i] <= 10 ^ 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
* @lc app=leetcode.cn id=122 lang=java
*
* [122] 买卖股票的最佳时机 II
*/

// @lc code=start
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) {
return 0;
}
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
}
// @lc code=end

89. Gray Code

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2

For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.

00 - 0
10 - 2
11 - 3
01 - 1

Example 2:

1
2
3
4
5
Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
Therefore, for n = 0 the gray code sequence is [0].
1
2
3
4
5
6
7
8
9
10
11
12
13
// @lc code=start
//公式 g(i) = i ^ (i / 2)
import java.util.List;
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<>();
//0001左移两位变成0100 = 4,左移三位等于8
for (int i = 0; i < 1 << n; i++) {
res.add(i ^ i >> 1);//除以2
}
return res;
}
}