LeetCode Learning 3

这次选了2题easy难度的题和1道normal难度的题。

2题easy都是关于字符串处理的,有相似之处所以一起写出来,加以对比。

389. Find the Difference

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

这里只需要最简单的方法就可以了,因为t只多了一个字母,把t每个字母找s中相同的字母,找到后删除s中此字母。若找不到则直接输出此字母。

class Solution {
public:
    char findTheDifference(string s, string t) {
        int lenn=t.size(),lenm=s.size();
                for(int i=0;i<lenn;i++){
                bool find=0;
                for(int j=0;j<lenm;j++){
                    if(t[i]==s[j]){find=1;s[j]=0;break;}
                }
                if(!find)return t[i];
            }
            return t[0];
    }
};


383. Ransom Note


Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return 
false. 



Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note.

这道题跟上一道非常相似,区别就是字母不只是差一个,然而这继续用之前的算法也是没问题的,只需要修改返回的值就可以了。
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int lenn=ransomNote.size(),lenm=magazine.size();
        if(lenn>lenm)return false;
        else{
            for(int i=0;i<lenn;i++){
                bool find=0;
                for(int j=0;j<lenm;j++){
                    if(ransomNote[i]==magazine[j]){find=1;magazine[j]=0;break;}
                }
                if(!find)return false;
            }
            return true;
        }
    }
};

238. Product of Array Except Self

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements ofnums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

本题难度为medium,主要是有了不能用除法和O(n)时间复杂度的限制。若无除法限制,这题只需求出全部数的积再除每个数就能轻松解决这个问题。我的思路是从前到后求每项的前项积的话是可以利用好前一项的前项积的结果的,而从后到前求每项后项积则刚好相反。因此只需要把从后到前把每一项后项积求出来并存到一个新数组中。然后就从前往后算前项积,每一位的前项积乘以存好的后项积就可以把结果存到输出数组中。这样就用O(n)的时间复杂度和空间复杂度解决了这个问题。

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> prob,out;
        int f2b=1,b2f=1,len=nums.size();
        prob.push_back(f2b);
        for(int i=1;i<len;i++){
            f2b *= nums[len-i];
            prob.push_back(f2b);
        }
        out.push_back(prob[len-1]);
        for(int i=1;i<len;i++){
            b2f *= nums[i-1];
            out.push_back(b2f*prob[len-i-1]);
        }
        return out;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值