菜鸡研究生的leecode刷题记录

菜鸡研究生的leecode刷题记录

2020年6月22日

Problem name: Palindrome Number
Difficulty: easy
Problem describe: Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Examples

//Submitted code in leecode
class Solution {
public:

int  maxsize = 32;
bool isPalindrome(int x) {
    if (x<0)
        return false;
    int number[maxsize];
    int i = 0,j;
    while(x!=0)
    {
        number[i++]=x%10;
        x /= 10;
    }
    for(j = 0; j<i ;j++)
    {
        if(number[j] != number[i-1])
            //if(number[j] != number[(i-1)--]) is not correct!
            return false;
        i--;
    }
    return true;
}
};
// Complete code
#include<iostream>
using namespace std;
int  maxsize = 32;
bool isPalindrome(int x) {
    if (x<0)
        return false;
    int number[maxsize];
    int i = 0,j;
    while(x!=0)
    {
        number[i++]=x%10;
        x /= 10;
    }
    for(j = 0; j<i ;j++)
    {
        if(number[j] != number[i-1])
            //if(number[j] != number[(i-1)--]) is not correct!
            return false;
        i--;
    }
    return true;
}
int main()
{
    int t;
    bool output;
    cin>>t;
    output = isPalindrome(t);
    cout<<boolalpha<<output<<endl;
    return 0;
    
}

Summary:

  • I use an integer 128 to definite the maximum length of an array, which is used to store the input number bit by bit.The reason why use the “128” to definite the maximum is 128 is the maximum length of integer in C++;
  • The object of an increment or decrement operator must be a variable, not an expression.For example, number[(i-1)++]) is illegal.
  • When we want to use cout function to output the bool variable with the form of “True” or “false” instead of “1” or “0”,we have to add the output format control expression cout<<boolalpha<<output<<endl;

2020年6月23日

Problem name: Longest Common Prefix
Difficulty: easy
Problem describe: Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.

在这里插入图片描述

在这里插入图片描述

// Submitted code in leecode
class Solution {
public:
    string longestCommonPrefix(vector<string> strs) {
        if(strs.empty()) 
        return "";
        string str="";
        for(int i=0;i < strs[0].size();i++){
            for(int j=1;j <strs.size();j++){
                if(strs[j].size()==i || strs[j][i] != strs[0][i])
                return str;
            }
            str+=strs[0][i];
        }
        return str;
    }
};

Summary:

  • For the string type variable,size() and length() have no difference.
  • The code is not complex, but it’s hard to think.

2020年6月24日

Problem name: Roman to Integer
Difficulty: easy
Problem describe: Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
在这里插入图片描述
For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

// Submitted code in leecode
class Solution {
public:
    int romanToInt(string s) {
        map<char,int> mp;
        mp['I']=1;
        mp['V']=5;
        mp['X']=10;
        mp['L']=50;
        mp['C']=100;
        mp['D']=500;
        mp['M']=1000;
        int ans=0;
        for(int i=0;i<s.length();i++){
            if(mp[s[i]]<mp[s[i+1]] && i<s.length()-1)
            ans-=mp[s[i]];
            else
            ans+=mp[s[i]];

        }
        return ans;
    }
};

Summary:

//We can define and assign values map directly like this:
map<char,int> mp={
            {'I',1},
            {'V',5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000}
        };

Problem name: Two Sum
Difficulty: easy
Problem describe: Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

在这里插入图片描述

// Submitted code in leecode
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> vec;
        for(int i=0;i<nums.size();i++){
            for(int j=i+1;j<nums.size();j++){
                if(nums[i]+nums[j]==target){
                vec.push_back(i);
                vec.push_back(j);
                return vec;                    
                }
            }
        }
        return vec;
    }
};



在这里插入图片描述
Summary:

  • vector use “push_back()” to add the value.
  • vector can’t use “length()” to get the length.We must use “size()”.

2020年6月25日

Problem name: Reverse Integer
Difficulty: easy
Problem describe: Given a 32-bit signed integer, reverse digits of an integer.Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
在这里插入图片描述

在这里插入图片描述

//  Submitted code in leecode
class Solution {
public:
    int reverse(int x) {
        long rl=0;
        for(;x;rl=rl*10+x%10,x/=10);
        return (INT_MAX<rl || rl<INT_MIN) ? 0:rl ;
    }
};

Summary:

  • NOTE that rl must be the long int type, otherwise the program can’t justify the situation of overflow.
  • We can use the for iteration to realize some awesome function.
  • This kinda problems about the operation of digits can use % and / to solve skillfully.
  • We should remember the usage of INT_MAX and INT_MIN.

2020年6月26日

Problem name: Valid Parentheses
Difficulty: easy
Problem describe: Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

在这里插入图片描述
在这里插入图片描述

//  Submitted code in leecode
class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
    for(int i=0;i<s.length();i++){
        if(s[i]=='('||s[i]=='['||s[i]=='{'){
            st.push(s[i]);
        }
        else if(s[i]==')'){
            if(st.empty() || st.top()!='(')
                return false;
            else
                st.pop();
        }
        else if(s[i]==']'){
            if(st.empty() || st.top()!='[')
                return false;
            else
                st.pop();
        }
        else if(s[i]=='}'){
            if(st.empty() || st.top()!='{')
                return false;
            else
                st.pop();
        }
        
    }
    if(st.empty())
        return true;
    else
        return false;
    
    }
};

Summary:

  • Stack with nothing can’t use .top() , otherwise the program will produce bugs.
  • We can optimize the code by “return st.size() == 0”;

2020年6月27日

Problem name: Remove Duplicates from Sorted Array
Difficulty: easy
Problem describe: 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.
在这里插入图片描述

// Submitted code in leecode
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int t=0;
        int size=nums.size();
        for(int i=1;i<size;i++){
            if(nums[i-t]==nums[i-t-1]){
                nums.erase(nums.begin()+i-t);
                t++;
            }
        }
        return nums.size();
        
    }
};

we also can rewrite it like this:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        for(int i=1;i<nums.size();){
            if(nums[i]==nums[i-1]){
                nums.erase(nums.begin()+i);
            }
            else
                i++;
        }
        return nums.size();
    }
};

在这里插入图片描述
Summary:

  • vector can’t use the length()
  • sometime, we can replace the increase of loop flag(like “i++”) into inside of the loop body, controlled by the result of some judge statements.In this way, the code can be more flexible.
  • Be careful if the loop judgement condition is constantly changing.

2020年6月28日

Problem name: Implement strStr()
Difficulty: easy
Problem describe: Implement strStr().

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

在这里插入图片描述
在这里插入图片描述

// submitted code in LeetCode
class Solution {
public:
    int strStr(string haystack, string needle) {
        return haystack.find(needle);
    }
};

Summary:

  • very easy by using the string library;
  • when the find() can’t find the actual result, it will return the string :: npos;the value of string :: npos is -1 ,it’s a unsigned_int constant(alse equal to 18446744073709551615 ,or 2^64-1);

2020年6月29日

Problem name: Search Insert Position
Difficulty: easy
Problem describe: 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.
在这里插入图片描述

//  submitted code in LeetCode
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int len=nums.size();
        if(target<nums[0])
        return 0;
        if(target==nums[len-1])
        return len-1;
        if(target>nums[len-1])
        return len;
        for(int i=0 ; i<len-1 ;i++ ){
            if(target==nums[i])
            return i;
            if(nums[i]<target && target<nums[i+1])
            return i+1;
        }   
        return 0;
    }
};

在这里插入图片描述
Summary:

  • Be careful when we think about the boundary condition, it’s pretty easy to neglect some particular examples.
  • The better solution:
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        for(int i=0 ; i<nums.size() ;i++ ){
            if(nums[i]>=target)
            return i;
        }   
        return nums.size();;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值