1048. Find Coins 解析

本文介绍了一种通过排序和二分查找的方法来判断是否能够使用两枚硬币恰好支付特定金额的算法。该算法首先对硬币面额进行排序,然后针对每一种硬币尝试寻找另一个能够与之组合成目标金额的硬币。

找两个硬币看能不能付钱,两个硬币必须正好等于要付的价格。

那就直接从小到大排序,然后从第一个元素开始,找价格减去当前硬币的价值,看能不能找到。

注意二分查找的最后位置。这个后面再找个时间研究下。里面其实有很多细节需要注意的。

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <queue>
#include <stack>
#include <cstring>

#define MAX 100010

using namespace std;

int n,m;
int coin[MAX];

int BinSearch(int num){
	int l = 0 ,r = n - 1;
	int pos = -1;
	while(l < r){
		int mid = (l + r + 1) /2 ;
		if(coin[mid] < num)
			l = mid + 1;
		else if(coin[mid] > num)
			r = mid - 1 ;
		else{
			pos = mid;
			break;
		}
	}
	return pos;
}

int main(){

	scanf("%d%d",&n,&m);
	for(int i = 0 ; i < n ; i++){
		scanf("%d",&coin[i]);
	}
	sort(&coin[0],&coin[n]);

	bool tag = false;
	for(int i = 0; i < n ;i++){
		int pos = BinSearch(m-coin[i]);

		if(pos>0 && pos != i){
			printf("%d %d\n",coin[i],coin[pos]);
			tag = true;
			break;
		}	
	}

	if(!tag)
		printf("No Solution\n");


	return 0;
}


from bs4 import BeautifulSoup import requests import lxml import openpyxl import os def get_html(url,headers,data): try: response = requests.get(url, headers=headers, params=data) if response.status_code == 200: return response.text else: print('请求失败') except Exception as e: print(e) def save_data(html): soup=BeautifulSoup(html,'lxml') node=soup.find_all('table') for sub_node in node: title=sub_node.find_all('h1')[2].get('title') likes=sub_node.find_all('span',{'class':'video-like-info video-toolbar-item-text'})[0].string coins=sub_node.find_all('span',{'class':'video-coin-info video-toolbar-item-text'})[0].string favorites=sub_node.find_all('span',{'class':'video-fav-info video-toolbar-item-text'})[0].string shares=sub_node.find_all('span',{'class':'video-share-info video-toolbar-item-text'})[0].string description=sub_node.find_all('span',{'class':'desc-info-text'})[0].string print(title, likes, coins, favorites, shares, description) sheet.append([title, likes, coins, favorites, shares, description]) if __name__ == "__main__": path='d:\\video' if not os.path.exists(path): os.mkdir(path) os.chdir(path) wb = openpyxl.Workbook() sheet = wb.active sheet.append(['标题', '点赞人数', '投币人数', '收藏人数', '转发人数','视频介绍']) url ='https://search.bilibili.com/all?vt=68706038&keyword=python&page=''' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36' } data={ 'page':0 } for page in range(0,11): data['page'] = page html = get_html(url,headers,data) save_data(html) wb.save('video.xlsx') 请将我的代码完善,我想要实现前十页视频爬取的相关内容
最新发布
06-13
当然可以!我们将逐一详细分析文件中的每一句话,并提供具体的实现步骤和技术细节。 ### 文件内容逐句分析 #### 1. 网站解析:利用 Chrome 查看网页源码,分析网站网页结构。 **实现步骤:** - **打开“哔哩哔哩”网站**,在搜索框中输入关键词 "python" 并访问以下链接: ```plaintext https://search.bilibili.com/all?vt=68706038&keyword=python ``` - **查看网页源码**: - **方法一**:右键点击网页任意空白处,选择“检查”或“检查元素”。 - **方法二**:按下键盘上的 `F12` 快捷键打开开发者工具。 - **分析网页结构**: - 浏览 HTML 源码,找到包含视频标题、点赞数、投币数、收藏数、转发数和简介的标签。通常这些信息位于 `<div>` 或 `<span>` 标签中,带有特定的类名或 ID。 #### 2. Python 语言编写爬虫代码,从“哔哩哔哩”网站中,搜索 python 视频相关信息。数据项包括:标题、点赞人数、投币人数、收藏人数、转发人数,以及视频的简单介绍。要求至少爬取 10 页数据。 **实现步骤:** - **安装依赖库**: ```bash pip install requests beautifulsoup4 selenium pandas sqlite3 ``` - **编写爬虫代码**: - 使用 `requests` 库获取网页内容。 - 使用 `BeautifulSoup` 解析 HTML。 - 使用 `Selenium` 模拟浏览器行为(如果需要处理 JavaScript 渲染的内容)。 示例代码框架: ```python import requests from bs4 import BeautifulSoup import time import sqlite3 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options # 初始化数据库连接 conn = sqlite3.connect('bilibili.db') cursor = conn.cursor() # 创建表 cursor.execute(''' CREATE TABLE IF NOT EXISTS videos ( title TEXT, likes INTEGER, coins INTEGER, favorites INTEGER, shares INTEGER, description TEXT ) ''') # 爬取多页数据 base_url = 'https://search.bilibili.com/all?vt=68706038&keyword=python' pages_to_scrape = 10 for page in range(1, pages_to_scrape + 1): url = f"{base_url}&page={page}" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 提取数据 video_elements = soup.find_all('li', class_='video-item matrix') for element in video_elements: title = element.find('a', class_='title').get_text(strip=True) likes = int(element.find('span', class_='like').get_text(strip=True)) coins = int(element.find('span', class_='coin').get_text(strip=True)) favorites = int(element.find('span', class_='favorite').get_text(strip=True)) shares = int(element.find('span', class_='share').get_text(strip=True)) description = element.find('div', class_='des hide').get_text(strip=True) # 插入数据库 cursor.execute('INSERT INTO videos (title, likes, coins, favorites, shares, description) VALUES (?, ?, ?, ?, ?, ?)', (title, likes, coins, favorites, shares, description)) # 提交事务 conn.commit() time.sleep(2) # 等待一段时间避免过于频繁请求 # 关闭数据库连接 conn.close() ``` #### 3. 将爬取的数据保存为 SQLite 数据库中,数据库名和表名自拟。 **实现步骤:** - **创建数据库**:在上面的代码中已经展示了如何使用 `sqlite3` 模块创建数据库和表。 - **插入数据**:每次爬取到新的视频信息时,将其插入到 SQLite 表中。 - **提交事务**:确保每次操作完成后调用 `conn.commit()` 来保存更改。 #### 4. 浏览数据库表的信息,抓取图片保存结果。 **实现步骤:** - **查询数据库**: - 使用 SQL 查询语句从表中检索数据。 - 示例代码: ```python import pandas as pd # 连接数据库并读取数据 conn = sqlite3.connect('bilibili.db') df = pd.read_sql_query('SELECT * FROM videos', conn) # 显示前几行数据 print(df.head()) # 关闭数据库连接 conn.close() ``` - **抓取图片保存结果**: - 可以使用 `matplotlib` 或 `seaborn` 库生成图表,并保存为图片文件。 - 示例代码: ```python import matplotlib.pyplot as plt # 绘制点赞数分布图 plt.figure(figsize=(10, 6)) plt.hist(df['likes'], bins=30, color='skyblue', edgecolor='black') plt.title('Distribution of Likes') plt.xlabel('Likes') plt.ylabel('Frequency') plt.savefig('likes_distribution.png') plt.show() ``` 请根据上述内容把完整代码写出来
06-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值