Daily exercises force Buckle

Search insertion position (simple)

Given a sorted array and a target, find the object in the array, and returns its index. If the target is not present in the array, it will be returned in sequence inserted position.

You may assume that no duplicate elements in the array.

Problem solving:

Simple binary search problem, because we know that when the presence of the target value among the sorted array is returned directly to mid index, when the target value is not included among the array is sorted, then we can analyze the results, the penultimate of the while loop in time, must be left = right, this time targeting a certain element as the first element is larger than the target value target, followed by a minus value right, exits the while loop. Therefore, we can see that this time index corresponding to the left target elements should be inserted target position.

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

};

The appearance of the number of columns (simple)

"Appearance number of columns" is a sequence of integers, beginning with the number 1, is the description of the preceding each item in the sequence. The first five are as follows:

The appearance of the number of columns
1 1
2 11
3 21
4 1211
5 111221

among them:

  • 1 is read as "One 1" ( "a a"), i.e., 11.
  • 11 is read as "two 1s" ( "two one"), i.e., 21.
  • 21 is read as "one 2", "one 1" ( "a two", "a a"), i.e., 1211.

Given a positive integer n (1 ≤ n ≤ 30), the n-th series term output appearance.

Note: Each sequence of integers will be represented as a string.

Problem solving:

This question is not difficult, it is important to understanding the problem, I think of it like before the interview at the US Mission line when asked this question, when is a way to give the appearance of puzzles series of top five let me write the sixth, did not react, now turn around and did not realize what this word count of the appearance of the column title abstract. Man of few words said, and then analyze this question: the appearance of the column is actually the number of repeats of the series described a number of our example to illustrate:

  • First, a first number is the number given in advance;
  • Next, a second number of the first number 1 will be described, which has a 1 1, the second number is 11;
  • Next, the second number to the third number 11 will be described, which has two 11 1, the third number is 21;
  • Next, a fourth number of the third number 21 will be described, which has a 21 and a 2 1, whereby the fourth number is 1211;
  • Next, the number of the fourth fifth number 1211 will be described, which has a 1211 1 1 and 2 1 and 2, and therefore the number of the fifth to 111,221.

This time we finally understand the meaning of the questions, to start our code:

class Solution {
public:
    string countAndSay(int n) {
        string str, res;
        res = "1";
        if (n == 1) return res;
        for (int i = 1; i < n; ++i)
        {   
            str = res;
            res = "";
            for (int j = 0; j < str.size();)
            {
                // c为计数器,k为当前描述数字对应下标
                int c=0,k=j;
                // 若k合法且str[k]重复则计数
                while(k<str.size()&&str[k]==str[j])
                {
                    ++k;
                    ++c;
                }
                res+=to_string(c)+str[j];
                j=k;
            }
        }
        return res;
    }
};

Finally, a word length (simple)

Given a string that contains only lowercase letters and spaces '' returns the length of the last word.

If the last word does not exist, 0 is returned.

Description: A word is defined by letters, but does not contain any spaces of a string.

Problem solving:

This question is the focus for special cases to consider:

  • The first case, "Hello World", at this time returns the last word length World 5
  • The second case, "Hello World", this time after the end of treatment spaces need to return to the last word length 5 in the World

After analyzing good special circumstances, to start writing code:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int last = s.size();
        for(int i = s.size() - 1; i >= 0; --i)
        {
            if(s[i] == ' ')
                last = i;
            else
                break;
        }
        int flag = 0;
        for(int i = 0; i < last; ++i)
        {
            if(s[i] == ' ')
            {
                flag = i + 1;
            }
        }
        return last - flag;
    }
};

Binary summation (simple)

Given two binary string, and return to their (expressed in binary).

Input is non-empty string and contains only numbers  1 and  0.

Problem solving:

Reverse sum is empty 0s, into the tag bits.

class Solution {
public:
    string addBinary(string a, string b) {
        string ans = "";
        int ca = 0;
        for(int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; --i, --j)
        {
            int sum = ca;
            sum += i >= 0 ? a[i] - '0' : 0;
            sum += j >= 0 ? b[j] - '0' : 0;
            ans = to_string(sum % 2) + ans;
            ca = sum / 2;
        }
        if (ca == 1)
            ans = to_string(ca) + ans;
        return ans;
    }
};

x squared (simple)

Achieve int sqrt (int x) function.

Computes and returns the square root of x, where x is a non-negative integer.

Since the return type is an integer, the integer part of the result to retain only the fractional part is rounded down.

Problem solving:

This question is also known as Newton's method, in other words that is half the deformation looking for. Before there is a blog about binary search, you can see a specific thing I read blog.

class Solution {
public:
    int mySqrt(int x) {
        long left = 0, right = x/2 + 1;
        while(left <= right)
        {
            long mid = left + ((right - left) >> 1);
            if(mid * mid > x)
            {
                right = mid - 1;
            }
            else
            {
                if((mid == x/2 + 1) || (mid+1) * (mid+1) > x)
                    return mid;
                else
                    left = mid + 1;
            }
        }
        return -1;
    }
};

Climbing stairs (simple)

Suppose you are climbing stairs. Need  n  order to reach your roof.

Every time you can climb one or two steps. How many different ways can climb to the roof of it?

Note: Given  n  is a positive integer.

Problem solving:

Derivation simply derived equation: A [n] = A [n-1] + A [n-2] Further Solution:

class Solution {
public:
    int climbStairs(int n) {
        if (n < 3)
            return n;
        const int len = n+1;
        int a[len];
        a[1] = 1;
        a[2] = 2;
        for(int i = 3; i <= n; ++i)
        {
            a[i] = a[i-1] + a[i-2];
        }
        return a[n];
    }
};

Remove sorts the list of repeating elements (simple)

Given a sorted list, delete all the duplicate elements, so that each element occurs only once.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* current = head;
        while (current != nullptr && current->next != nullptr) {
            if (current->next->val == current->val) {
                current->next = current->next->next;
            } else {
                current = current->next;
            }
        }
        return head;
    }
};

The same tree (simple)

Given two binary tree, write a function to check whether they are identical.

If the two are identical in structure tree, and the nodes have the same value, they are considered identical.

Problem solving:

Recursive solution to:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p == nullptr && q == nullptr)
            return true;
        else if(p == nullptr || q == nullptr)
            return false;
        else if(p->val != q->val)
            return false;
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};

 

Published 37 original articles · won praise 42 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_42570248/article/details/103956338