从零开始的leetcode刷题 (C++,Python,Java)(三)

第21题

//0ms? 14.4MB
//重新提交只有12ms了,降速了,简单题,不赘述
//c++
class Solution {
public:
	ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
		ListNode* result,*nowplace;
		ListNode* left, *right;
		left = l1;
		right = l2;
		if (left == nullptr || right == nullptr)
		{
			return left ? left : right; //如果left为真 返回left 如果left不为真 返回right
		}
		else
		{
			result = left->val <= right->val ? left : right;
            nowplace=result;
            //cout<<nowplace->val<<endl;
			if (left->val <= right->val)
			{
				left = left->next;
			}
			else
			{
				right = right->next;
			}

			while (left && right)
			{
                //cout<<nowplace->val<<endl;
                //cout<<left->val<<" "<<right->val<<endl;
				if (left->val <= right->val)
				{
					nowplace->next = left;
                    nowplace = nowplace->next;
					left = left->next;
				}
				else
				{
					nowplace->next = right;
                    nowplace = nowplace->next;
					right = right->next;
				}
			}
			//直到一方元素比较完毕
			ListNode* p = left ? left : right;
			while (p)
			{
				nowplace->next = p;
                nowplace=nowplace->next;
				p = p->next;
			}
			return result;
		}
	}
};

第22题

#36ms
#15.3MB
class Solution:
    Listp=[]
    def generateParenthesis(self, n: int) -> List[str]:
        self.Listp=[]
        str=""
        self.Produce(n,str,0,n)
        return self.Listp
    def  Produce(self,n,str,leftnumber,usenumber):

        if usenumber>0: #表示还是可以塞一个左括号
            temp= str+"("
            self.Produce(n, temp,leftnumber+1,usenumber-1)
        if leftnumber>0:
            temp=str+")"
            self.Produce(n,temp, leftnumber-1,usenumber)
        if usenumber==0 and leftnumber==0:
            self.Listp.append(str)

第23题

//暴力算法
//好像分治什么的也可以,但是我懒得写了
//296ms 12.9MB
//如果是利用21题的代码,时间可以勉强压进250ms
class Solution {
public:
	ListNode* mergeKLists(vector<ListNode*>& lists) {
		int length = lists.size();
		ListNode* result = nullptr;
		ListNode* tempresult = result;
		if (length == 0)
		{
			return result;
		}
		else if (length == 1)
		{
			return lists[0];
		}
		else
		{
			ListNode**p = new ListNode*[length]; //这是一个指针数组
			int count = 0;
			bool* bp = new bool[length];
			for (int i = 0; i < length; i++)
			{
				if (lists[i])
				{
					bp[i] = true;
				}
                else
                {
                    count++;
                    bp[i]=false;
                }
                p[i]=lists[i];
			}
			while (count < length)
			{
				ListNode* small=nullptr;
				int smallnumber = INT_MAX;
				int smallplace = 0;
				for (int i = 0; i < length; i++)
				{
					if (bp[i])
					{
						if (p[i]->val < smallnumber)
						{
							small = p[i];
							smallnumber = p[i]->val;
							smallplace = i;
						}
					}
				}
				//这样筛选出了最小的元素
				cout << small->val << endl;
                if(tempresult==nullptr)
                {
                    tempresult=small;
                    result=tempresult;
                }
                else
                {
                    tempresult->next=small;
                    tempresult=small;
                }
                small=small->next;
                p[smallplace]=p[smallplace]->next;
				if (small == nullptr)
				{
					bp[smallplace] = false;
					count++;
				}
			}
			return result;
		}
	}
};

第24题

//4ms 7.4MB
//可以接受 不算很难
//C++
class Solution {
public:
	ListNode* swapPairs(ListNode* head) {
		ListNode* result = head;
		ListNode* phead = new ListNode(0);
		phead->next = head;
		if (result == nullptr || result->next == nullptr)//表明只有0/1个元素
		{
			return head;
		}
		else
		{
			int count = 0;
			ListNode** p = new ListNode * [3];
			p[0] = phead;
			while (head)
			{
				count++;
				p[count] = head;
				head = head->next;
				if (count == 2)
				{
					this->DO_it(p[0], p[1], p[2], p);
                    head=p[0]->next;
					count = 0;
				}
			}
			return phead->next;
		}
	}
	void DO_it(ListNode* pre, ListNode* one, ListNode* two,ListNode** p)
	{
		pre->next = two;
		ListNode* temp = two->next;
		two->next = one;
		one->next = temp;
		p[0] = one;
	}
};

第25题

//我写的代码,通常都会比别人得长一些
//12ms 11.3MB
//截取指定长度,然后反转链表即可,基础的数据结构算法
//装起来了(笑)明明debug弄了挺久的好吧。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
	ListNode* reverseKGroup(ListNode* head, int k) {
		ListNode* phead = new ListNode(0);
		phead->next = head;
		if (k == 1)
		{
			return head;
		}
		else
		{
			int count = 0;
			ListNode* pre = phead;
			ListNode* begin=nullptr;
			ListNode* end = nullptr;
			bool flag = false;
			while (head)
			{
				if (!flag)
				{
					begin = head;
					flag = true;
				}
				count++;
				if (count == k)
				{
					end = head;
					count = 0;
					pre=this->Do_it(pre, begin, end);
                    head=pre->next;
                   // cout<<head->val<<endl;
					flag = false;
				}
                else
                {
                    head = head->next;
                }
                
			}
			return phead->next;
		}
	}
	ListNode* Do_it(ListNode* pre, ListNode* begin, ListNode* end)
	{
        //cout<<pre->val<<" "<<begin->val<<" "<<end->val<<endl;
		ListNode* Pbegin = begin;
        ListNode* Pendnext=end->next;
		begin = begin->next;
		while (begin != Pendnext)
		{
			ListNode* prenext = pre->next;
			ListNode* beginnext = begin->next;
			pre->next = begin;
			begin->next = prenext;
			begin = beginnext;
		}
		//这一套下来 begin'指向的是原来end 后的元素
		//当然也可能是nullptr
		//但是我们得把链表接起来
		Pbegin->next = begin;
		return Pbegin;
	}
};

第26题

#python
#40ms 15.6MB
#下次还填非常简单
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        length=len(nums)
       # print(length)
        realpoint=0
        nowpoint=1
        if length==1 or length==0:
            return length
        prenumber=nownumber=nums[0]
        count=1
        while nowpoint < length:
            nownumber=nums[nowpoint]
            if nownumber==prenumber:
                pass
            else:
                realpoint+=1
                nums[realpoint]=nums[nowpoint]
                count+=1
            nowpoint+=1
            prenumber = nownumber
       # print(nums)
        return count

第27题

#python 简单题
#执行用时:32 ms, 在所有 Python3 提交中击败了75.68%的用户
#内存消耗:14.8 MB, 在所有 Python3 提交中击败了84.67%的用户
class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        temp=0
        length=len(nums)
        return_length=0
       #print(length)
        for i in range(0,length):
            if nums[i]!=val:
                nums[temp]=nums[i]
                temp+=1
                return_length+=1
        #print(nums)
        return return_length

第28题
KMP算法
KMP算法参考

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle:
            #如果needle是空字符串返回0
            return 0
        length=len(needle)
        next=[-1 for i in range(0,length)]

        x=0
        now=1
        next[0]=0 #第一个元素显然是0
        while now < length:
            if needle[now]==needle[x]:
                next[now]=x+1
                x+=1
                now+=1
            elif x:
                x=next[x-1]
            else:
                #x=0
                next[now]=0
                now+=1
        #比对环节
        mains=0
        nes=0
        while nes!=len(needle) and mains<len(haystack):
            if haystack[mains]==needle[nes]:
                mains+=1
                nes+=1
            elif nes != 0:
                temp=needle[nes]
                nes=next[nes-1] #但是这里存在一个问题
                #如果 nes所在元素与mains所在元素不匹配
                #但是新的nes 元素可能依然与旧的nes元素相同
                #那下面的比较依然是无意义的  例如 12123xxxxx 【原串】 字串为12121 1与3不匹配
                #那么 根据next可以知道 这时候 应该将nes转移到2号位【从0开始计数】也就是1
                # 12123xxxxx                                      12123xxxxx
                # 12121 【匹配失败】                           12121
                #显然这个比较是无意义的
                while nes!=0 and temp==needle[nes]:
                    temp=needle[nes]
                    nes=next[nes-1]
            else:
                mains+=1

        if nes==length:
            return mains-length
        else:
            return -1

第29题

class Solution {
public:
	int divide(int D, int d) {
		int result = 0;
		if (D == 0)
		{
			return 0;
		}
		else if (d == 1)
		{
			return D;
		}
		else if (d == -1)
		{
			if (D == INT_MIN)
			{
				return INT_MAX;
			}
			else
			{
				return D * -1;
			}
		}
		else
		{
			int x = (D > 0 && d > 0) || (D < 0 && d < 0) ? 1 : -1;
			int TempD = -(abs(D));
			int Tempd = -(abs(d));
			int tempnumber = 0;
			while (TempD<=Tempd)
			{
				 int tempresult=0;
				if (tempnumber + Tempd < TempD) //表明溢出 爆炸
				{
					return result;
				}
				else
				{
					tempnumber += Tempd;
					++tempresult;
				}
				while (tempnumber > INT_MIN / 2 && tempnumber * 2 > TempD)
				{
					tempresult *= 2;
					tempnumber *= 2;
				}
				//这里再也不能更大了
				TempD -= tempnumber;
				result += tempresult;
				tempnumber = 0;
			}
			return result*x;
		}
	}
};

第30题

//粗暴解法
//执行用时:360 ms, 在所有 C++ 提交中击败了22.03%的用户
//内存消耗:38.1 MB, 在所有 C++ 提交中击败了30.66%的用户
class Solution {
public:
	vector<int> findSubstring(string s, vector<string>& words) {
		vector<vector<int>> nexts;
		int wordslength = words.size() * words[0].length();
		map<string, int> hashmap;
		for (int i = 0; i < words.size(); i++)
		{
			hashmap[words[i]] += 1;
		}
		vector<int> canbenumber = Process_search(nexts, s, hashmap);
		vector<int> result;
		for (int i = 0; i < canbenumber.size(); i++)
		{
			int startnumber = canbenumber[i];
			if (startnumber + wordslength <= s.length())
			{
				string checkstring = s.substr(startnumber, wordslength);
				if (Process_Check(hashmap, checkstring, words[0].length()))
				{
					result.push_back(startnumber);
				}
			}
		}
		return result;
	}
	vector<int> Process_search(vector<vector<int>>& nexts, string s,map<string,int>& wordmap)
	{
		vector<string> words;
		map<string, int>::iterator it;
		for (it = wordmap.begin(); it != wordmap.end(); it++)
		{
			words.push_back(it->first);
		}
		int number = words.size();
		int wordlength = words[0].length();
		vector<int> result; //返回的数组
		for (int i = 0; i < number; i++)
		{
			int x = 0;
			int now = 1;
			vector<int> tempnext;
			tempnext.resize(wordlength);
			tempnext[0] = 0;
			while (now < wordlength)
			{
				if (words[i][now] == words[i][x]) //如果两个元素相等
				{
					tempnext[now] = x + 1;
					++x;
					++now;
				}
				else if (x) //如果x不为澪 但是两个元素不相等
				{
					x = tempnext[x - 1];
				}
				else //如果x已经为0
				{
					tempnext[now] = 0;
					++now;
				}
			}
			nexts.push_back(tempnext);
		}
		//到这里所有的next数组已经生成
		for (int i = 0; i <words.size(); i++) //我们查找每一个符合条件的起始点
		{
			int Snum = 0;
			int snum = 0;
			while (Snum < s.length())
			{
				if (s[Snum] == words[i][snum]) //如果相等
				{
					Snum++;
					snum++;
				}
				else if (snum)
				{
					snum = nexts[i][snum - 1];
				}
				else
				{
					Snum++;
				}
				if (snum == wordlength)
				{
					if (find(result.begin(), result.end(), Snum - wordlength) == result.end()) //如果不存在该元素
					{
						result.push_back(Snum - wordlength);
					}
					Snum -= wordlength;
					Snum++;
					snum = 0;
				}
			}
		}
		return result;
	}
	bool Process_Check(map<string,int> hashmap, string temps,int wordlength)
	{
		int now = 0;
		while (now < temps.length())
		{
			string p = temps.substr(now, wordlength);
			now += wordlength;
			if (hashmap.find(p) == hashmap.end())
			{
				return 0;
			}
			else
			{
				hashmap[p] -= 1;
				if (hashmap[p] < 0)
				{
					return 0;
				}
			}
		}
		map<string, int>::iterator it;
		int T = 0;
		for (it = hashmap.begin(); it != hashmap.end(); it++)
		{
			T -= it->second;
		}
		if (T == 0)
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
};
//更暴力 也更laji的蒜贩
//时间直接上784ms去了
class Solution {
public:
	vector<int> findSubstring(string s, vector<string>& words) {
		vector<int> result;
		int start=0;
		int wordslength = words.size() * words[0].length();
		int end = start + wordslength -1;
		map<string, int> hashmap;
		for (int i = 0; i < words.size(); i++)
		{
			hashmap[words[i]] += 1;
		}
		while (end < s.length())
		{
			string tempstring = s.substr(start, wordslength);
			if (Process_Check(tempstring, words[0].length(), hashmap))
			{
				result.push_back(start);
				//cout << start << endl;
			}
			start++;
			end++;
		}
		return result;
	}
	bool Process_Check(string tp, int wordlength, map<string, int> hashmap)
	{
		int start = 0;
		//cout << tp << endl;
		while (start + wordlength <= tp.length())
		{
			string tempstring = tp.substr(start, wordlength);
			start += wordlength;
			//cout << tempstring << endl;;
			if (hashmap.find(tempstring) == hashmap.end())
			{
				return 0;
			}
			else
			{
				if (--hashmap[tempstring]<0)
				{
					return 0;
				}
			}
		}
		int  count = 0;
		map<string, int>::iterator it;
		for (it = hashmap.begin(); it != hashmap.end(); it++)
		{
			count += it->second;
		}
		if (count == 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值