The journey of the Leetcode DAY1(704.Binary Search&27.Remove Element)

Update

Code Review:
add day1 in the title.
add comments in the code area.

Code Review 2:
add details under the problems with examples.

Preface

This is my first blog to record my journey of the Leetcode.
I am a freshman who transferred to major in CS.
I participated in a training camp to strengthen my coding ability and try to learn blog writing and improve my English writing. That’s why I wrote in English.
Tell the truth, It’s hard for me to make them all good. But I have to TRY something new to escape my comfortable zone.

1.Array Basic

As we all know, Array is one of the basic data structures.
Today we make some notes of Array.

  • The index of the Array starts from 0.
  • The address of the array memory space is contiguous.
  • You can’t delete the Element, only overwritten.

2.Binary Search

Leetcode Link: 704.Binary Search
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.
Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

Constraints:

1 <= nums.length <= 104
-104 < nums[i], target < 104
All the integers in nums are unique.
nums is sorted in ascending order.

Analysis and Solution

This method shows us an easy way to solve it efficiently instead of direct search.

  • Define the border of the numbers. include left and right.

when we define the left and right,we make left included ? and right included?
there are two methods we usually define them. what we need to do is we need to code accord with what we defined.

one is to make left included and right included.

the other is to make left included and right not included.

  • Define the new left and new right in the coding process.

make left included and right included.

if middle >target; the new right should be middle -1 because of right is included according to what we defined earlier.
if middle < target ;the new left should be middle +1.same as before.

make left included and right not included.

if middle >target; the new right should be middle.
if middle < target ;the new left should be middle +1.

Leetcode C++ 1 as followings(make left included and right included):

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int left = 0; //define a left boundary
        int right = nums.size() - 1;//define a right boundary
        while(left <= right){
            int mid = left + ((right - left)>>1);//mid value = (left + right)/2; left + ((right - left)>>1; to prevent overflow. ">>" is more efficient than "/2"
            if (nums[mid] == target) {
                return mid;//return the value when found the value
            } else if (nums[mid] > target) {//situation 1
                right = mid - 1;//change the boundary
            } else {//situation 2
                left = mid + 1;//change the boundary
            }
        }
        return -1;
    }
};

Leetcode C++ 2 as followings(make left included and right not included):

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int left = 0; //define a left boundary
        int right = nums.size();//define a right boundary
        while(left < right){
            int mid = left + ((right - left)>>1);//mid value = (left + right)/2; left + ((right - left)>>1; to prevent overflow. ">>" is more efficient than "/2"
            if (nums[mid] == target) {
                return mid;//return the value when found the value
            } else if (nums[mid] > target) {//situation 1
                right = mid;//change the boundary
            } else {//situation 2
                left = mid + 1;//change the boundary
            }
        }
        return -1;
    }
};

3.Remove Element

Leetcode Link: 27.Remove Element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = […]; // Input array
int val = …; // Value to remove
int[] expectedNums = […]; // The expected answer with correct length.
// It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,,]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,,,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100

1.Violent Solution

Just use twice for loop, first for loop is to traverse the whole Array second for loop is to update the new Array.

Leetcode C++ 1 as followings:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int n = nums.size();//define n = size of nums
        for(int i=0;i<n;i++){//for loop; traverse n
            if(nums[i]==val){//find the target
                for(int j=i+1;j<n;j++){//defina j; traverse from i=1 to the end
                    nums[j-1]=nums[j];//move 1 to overwrite the former,which means remove element 
                }
                i--;//move i
                n--;//n - 1,cause by remove element
            }
        }
        return n;
    }
};

2.Double Pointer

Finished the twice for loop under the only one for loop via double pointer.

Define the first and second pointer

First pointer is to traverse the whole Array, pick the elements that do not equal the value.
Second pointer is to save the elements picked from the first pointer.

Leetcode C++ 2 as followings:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int n = nums.size();
        int left=0;//define a left pointerr
        for (int right = 0; right < n; right++) {//define a right pointer,traverse n
            if (nums[right] != val) {//condition of if
                nums[left++] = nums[right];//right value will assign to left ,then left + 1,left save all the elements except target
            }
        }
        return left;//left is what we demand; the new n
    }
};

Conclusion

A good start is a half of success.
You know you need to keep moving even if come across so many troubles.
keep fighting!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值