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();
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章