LeetCode: Search Insert Position, Count and Say, Maximum Subarray, Length of Last Word

来源:互联网 发布:昆士兰大学软件专业 编辑:程序博客网 时间:2024/06/13 22:28

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.

"""6 ms, beats 23.63%时间O(n)"""class Solution {public:    int searchInsert(vector<int>& nums, int target) {        for (int i=0; i<nums.size(); i++){            if (target <= nums[i])                return i;        }        return nums.size();    }};
"""二分查找,6 msO(log n)"""class Solution {public:    int searchInsert(vector<int>& nums, int target) {        int begin = 0;        int end = nums.size();        while (begin < end){            int mid = floor((begin + end)/2);            if (target == nums[mid])                return mid;            if (target > nums[mid]){                begin = mid + 1;            }            else                end = mid; // 注意不-1        }        return begin;    }};

Count and Say
1. 1
2. 11
3. 21
4. 1211
5. 111221
每一个值是前一个值的读音:
1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.

"""3 ms, beats 23.64%迭代求解,扫描字符串的每一位进行count。注意边界情况的处理。"""class Solution {public:    string count_and_say(string t_str){        string result = "";        char anchor = t_str[0];        int num = 0;        for (int i=0; i<t_str.length(); i++){            if (t_str[i] == anchor)                 num ++;            else{                result.append(to_string(num));                result += anchor;                anchor = t_str[i];                num = 1;                        }                  if (i == t_str.length()-1){  //小心                result.append(to_string(num));                result += anchor;            }        }        return result;    }    string countAndSay(int n) {        string temp = "1";        for (int i=2; i<=n; i++)            temp = count_and_say(temp);        return temp;    }};

Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

"""题目似曾相识,好像算法课上讲过。显然暴力搜索不是好办法。- 直接的暴力搜索是O(n^3)或O(n^2)(利用数组求和的局部相关性)。- 分而治之- 最大子串的特点: 前后一定是负数,相邻任意长度的子串求和都是负数这里先实现一个分治法:13 ms, beats 12.91%O(nlog(n))"""class Solution {public:    int maxsub(vector<int>& nums, int begin, int end){        if (begin == end)            return nums[begin];        int middle = (begin + end)/2;        int sum = 0;        int middle_left = INT_MIN;  //        int middle_right = INT_MIN;        for (int i=middle+1; i<=end; i++){            sum += nums[i];            middle_right = max(middle_right, sum);        }        sum = 0;        for (int i=middle; i>= begin; i--){            sum += nums[i];            middle_left = max(middle_left, sum);        }        return max(maxsub(nums, begin, middle), max(maxsub(nums, middle+1, end), middle_left+middle_right));     }    int maxSubArray(vector<int>& nums) {        return maxsub(nums, 0, nums.size()-1);    }};
"""这里实现一下课件上的扫描法, O(n)9 ms, beats 37.70%"""class Solution {public:    int maxSubArray(vector<int>& nums) {        int max_so_far = INT_MIN;        int max_end_here = 0;        for (int i=0; i<nums.size(); i++){            max_so_far = max(max_so_far, max_end_here + nums[i]);            max_end_here = max(max_end_here + nums[i], 0);        }        return max_so_far;    }};

Length of Last Word
Input: “Hello World”
Output: 5

"""字符串末尾还有empty。。3 ms, beats 26.54%"""class Solution {public:    int lengthOfLastWord(string s) {        int non_empty = 0;        for (int i=s.length()-1; i>=0; i--){            if (s[i] != ' ')                non_empty += 1;            if (non_empty > 0){                if (s[i] == ' ' || i == 0)                    return non_empty;            }        }        return 0;    }};
"""更简洁的写法"""class Solution {public:    int lengthOfLastWord(string s) {         int len = 0, tail = s.length() - 1;        while (tail >= 0 && s[tail] == ' ') tail--;        while (tail >= 0 && s[tail] != ' ') {            len++;            tail--;        }        return len;    }};
原创粉丝点击