代码随想录第一天| leetcode704. 二分查找、27. 移除元素

leetcode 704 二分查找:

主要是维护区间的合法化;

左闭右闭区间:

class Solution {
public:
    int search(vector& nums, int target) {
        int mid,left=0, right=nums.size() -1;
        while (left <= right){
            mid=(left + right)/2;
            if (nums[mid] == target ) {
                return mid;
            }
            else if(nums[mid] > target){
                right = mid - 1;
            }
            else if (nums[mid] < target){
                left = mid + 1; 
            } 
        }
        return -1;
     }
};

 左闭右开区间的写法:

class Solution {
public:
    int search(vector& nums, int target) {
        int mid,left=0, right=nums.size();
        while (left < right){
            mid=(left + right)/2;
            if(nums[mid] > target){
                right = mid;
            }
            else if (nums[mid] < target){
                left = mid + 1; 
            }
            else if (nums[mid] == target ) {
                return mid;
            }  
        }
        return -1;
     }
};

leetcode 27 移除元素:

暴力法:

class Solution {
public:
    int removeElement(vector& nums, int val) {
        //erase
         int leng=nums.size();
         int i;
         int j;
         for (i=0; i

双指针法:

fast用来寻找新数组的下一个元素,low用来确定新数组下个元素的下标。

class Solution {
public:
    int removeElement(vector& nums, int val) {
        //erase
       int fast, low=0; 
       int len = nums.size();
       for(fast=0; fast < len ; fast++){
           if(nums[fast] != val){
               nums[low] = nums[fast];
               low++;
           }
       }
    return low;
    }
};

你可能感兴趣的:(leetcode,算法,数据结构)