LeedCode-Easy 21,26,27,28,35

Merge Two Sorted Lists

题目原文

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

题目大意

合并两个排列序列并且返回一个作为新的序列.这个新的序列应该成为新的有序序列

我对链表忘记掉了,用的是大佬的代码

class Solution {
public:
   ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
    if (!l1)         // If no l1, return l2
        return l2;
    if (!l2)         // If no l2, return l1
        return l1;
    if (!l2 && !l1)  // If neither, return NULL;
        return NULL;

    ListNode* head; // The pointer we will use to construct a merged list


    if (l1->val < l2->val)   // If l1 less than l2
    {
        head = l1;          // We start at l1
        l1 = l1->next;      // and iterate l1
    }
    else                    // If l2 less than l1
    {
        head = l2;          // We start at l2
        l2 = l2->next;      // and iterate l2
    }

    ListNode* ret = head;   // We need to save the addres of the head of the list

    while (l1 && l2)         // While both input lists have values
    {
        if (l1->val < l2->val)   // Compare the current values, if l1 is less
        {
            head->next = l1;    // Append the merged list with l1's current address
            l1 = l1->next;      // Advance l1
        }
        else                    // Else, l2 had the low value
        {
            head->next = l2;    // Append l2 to the list
            l2 = l2->next;      // Advance l2
        }
        head->next->next = NULL;    // Append a NULL teminator to the list
        head = head->next;          // Advance the merged list
    }

    // Lastly, if list were different lengths, we need to append the longer list tail to the merged list

    if (l1)
        head->next = l1;
    else if (l2)
        head->next = l2;

    return ret; // Return the starting address of head that we saved.


}
};

Remove Duplicates from Sorted Array

题目原文

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

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

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

题目大意

就是给你一个数组,要你算出里面不重复数一共有多少,而且要去掉那些重复的

代码如下:

https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/12112/My-C%2B%2B-O(n)-solution

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() == 0)
            return 0;
        int i = 0, j = 1;
        //i是从头开始遍历的坐标
        //j是后来终止的符号
        while (j < nums.size())
        { 
            //如果j不等于i的话
            if (nums[j] != nums[i])
                //++i用的是i+1后的值
                nums[++i] = nums[j];
            j++;
        }
        return i + 1;
    }
};

Remove Element

题目原文

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

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

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

生词如下:

instances 实例

modifying 修饰

题目大意:

输入一组数和一个数,然后再这组数字中去掉这个数.就OK了.要求不能用数组,空间复杂度为1

我的代码如下:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int length = nums.size();
        for (int i = 0; i < length; i++) {
            if (nums[i] == val) {
                length = length - 1;
                //最基础的左移代码
                for (int j = i + 1; j < nums.size(); j++) {
                    nums[j - 1] = nums[j];
                }
            }
            //为了避免 两个重复的一起出现的情况
            if (nums[i] == val) i--;
        }
        return length;
    }
};

网上的优秀代码

① 简化版

地址:https://leetcode.com/problems/remove-element/discuss/12680/A-simple-c%2B%2B-solution

/*
	核心思路,就是遍历,然后把不是的赋值给原数组
*/
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
    int idx=0;
    for(int i=0;i<nums.size();i++) {
        if(nums[i]!=val) {
            //两句核心代码,你只有一个一个的给就OK了,不是的给原数组
            nums[idx] = nums[i];
            idx ++;
        }
    }
    return idx;
}
};

https://leetcode.com/problems/remove-element/discuss/480364/C%2B%2B-100-using-STL

② STL版

/*
	核心思路,就是遍历,然后直接删除不是的
*/
int removeElement(vector<int>& n, int val) 
{
    n.erase(std::remove(n.begin(), n.end(), val), n.end());
    /*
    	这一句的代码
    	std::remove(n.begin(),n.end(),val)	就是把n.begin到n.end()中的val都删除掉,但是那个空间还是在的而且返回的是我们
    	删除之后的最后一个位置
    	n.erase(it,n.end())	就是删除最后几个?的位置
    */
    return n.size();
}

Implement strStr()

题目原文

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

生词如下:

Implement 实施

occurrence 出现

Clarification 解释

题目大意

就是给你两个String类型的数字,让你算第二个String在第一个String类型里第一次出现的地方,如果第二个String为空的话,默认返回为0

我的代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.size() == 0) return 0;   //特殊情况为空的时候
        //index用来表示在needle里面递增的下标,flag用来判断有没有出现
        int index = 0, flag = 1;
        for (int i = 0; i < haystack.size(); i++) {
            index = 0;
            if (haystack[i] == needle[index]&&(i+needle.size()-1)<=haystack.size()) {
                for (int j = i; j <= needle.size() + i-1; j++) {
                    if (haystack[j] == needle[index++])
                        flag = 0;
                    else {
                        flag = 1;
                        break;
                    }
                }
                if (flag == 0)
                    return i;
            }
        }
        return -1;
    }
};

网上的优秀代码

① 一行的代码

https://leetcode.com/problems/implement-strstr/discuss/12982/3-different-solutions-1581-lines-C%2B%2B

一个函数解决问题

class Solution {
public:
    int strStr(string haystack, string needle) {
        return haystack.find(needle);
    }
};

② KMP代码-快,好

https://leetcode.com/problems/implement-strstr/discuss/452070/C%2B%2B-0ms-less100-8.9MB-less95.71

KMP我不理解,这里只是贴一下

static auto x = []() {ios_base::sync_with_stdio(false); cin.tie(NULL); return NULL; }();    //可以让代码运行变快

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.empty()) { return 0; }
        else if (needle.size() > haystack.size()) { return -1; }

        for (short int i = 0; i < (haystack.size() - needle.size() + 1); ++i) {
            for (short int j = 0; j < needle.size(); ++j) {
                if (haystack[i + j] != needle[j]) { break; }
                else if (j + 1 == needle.size()) { return i; }
            }
        }
        return -1;
    }
};

Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

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

Example 2:

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

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

题目大意

给一个目标数,和一组排列好的数据,如果一组数据中,有这个目标数,

那就返回它在数组中的下标

如果没有,那就返回,如果插入这个数据的下标

举个例子:

一组数据: 1 2 3 4 9

目标数: 8

那就应该返回 4

如果目标数为 :0

那就应该返回 : 0

我写的代码如下:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
	
	if(nums[0]>target){
		return 0;
	}
	if(nums[nums.size()-1]<target){
		return nums.size();
	}
	for(int i=0;i<nums.size();i++){
		if(target == nums[i]){
			return i;
		}
		else if(i!=nums.size()&&(target>nums[i]&&target<nums[i+1])){
			return i+1;
		}
	}
	return 0;
    }
};

别人的优秀代码

参考地址

地址一

地址二

一行地址决问题

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        return lower_bound(begin(nums), end(nums), target) - begin(nums);
    }
};

lower_bound( begin,end,num)是一个二分查找的函数,从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标

二分查找的具体实现

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        auto first = nums.begin(), last = nums.end();
        while (first < last) {
            auto mid = first + ((last - first) >> 1);
            if (*mid < target) {
                first = mid + 1;
            } else {
                last = mid;
            }
        }
        return first - nums.begin();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值