At the end of the exam, the average score of the class only got the second grade, the teacher in charge then asked: everyone knows the world’s first peak Qomolangma, anyone know the world’s second peak is what? Just as the teacher was going to continue to speak, he heard a voice in the corner: “K2”
preface
2018.11.23 clock in today’s topic leetcode28: https://leetcode-cn.com/problems/implement-strstr/description/
Yesterday’s problem
The title
Leetcode27 – Remove element every day https://leetcode-cn.com/problems/remove-element/description/ English link https://leetcode.com/problems/remove-element/description/
Detailed questions
The title,
Train of thought
- This topic looked at the topic is very long, thought a little difficult actually ok, in fact, general;
- It’s the idea of a double pointer, begin and end, one before and one after, because what you want to end up with is the value of val first; That is, begin finds a value other than val, begin++; Until the value of begin equals val, the value of val referred to by begin needs to be moved behind;
- End is at the end of the array. If end finds val (because val is at the end of the array), end–, until the value of end is not equal to val.
- So find these two values and swap them, swap the values of begin and end; Then repeat the process
code
1class Solution {
2 public int removeElement(int[] nums, int val) {
3 int count = 0;
4 int begin = 0;
5 int end = nums.length - 1;
6 while(begin <= end)
7 {
8 while(begin < nums.length && nums[begin] ! = val)
9 begin++;
10 while(end >= 0 && nums[end] == val)
11 {
12 count++;
13 end--;
14 }
15 if(begin >= end || begin >= nums.length || end < 0)
16 break;
17 int temp = nums[begin];
18 nums[begin] = nums[end];
19 nums[end] = temp;
20 }
21 return nums.length - count;
22 }
23}
Copy the code
The code on
- 8-9 Nums [begin] is not equal to val, begin++, until val is equal to nums
- Nums [end] = nums[end];
- Lines 15 and 16 end the loop
- Lines 17-19 swap the values of begin and end (that is, swap the non-val value after the array with the val value before the array)
- Line 21: The length of the array minus the value of count is the number of non-val values, which is the length of the array to be returned.
conclusion
# 2018.11.23 clock
The author, Chogory, is a computer master of Harbin Institute of Technology and a Java engineer of Baidu. Welcome to follow my wechat official account: The official account has 3T programming resources, and my friend and I (baidu C++ engineer) compiled nearly 200 MB of required Java and C++ interview experience during the autumn recruitment, and there is a leetcode punch-card group and technical exchange group every day, welcome to follow.