victory的博客

长安一片月,万户捣衣声

0%

11.盛最多水的容器

题目描述

给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器。

题目链接

思路

  1. 双指针法
    height=[a1,a2,…,an]
    起始两个指针l、r分别指向n个非负整数的两端,接着计算容器容积area = min(height[l], height[r]) * (r - l),然后移动l、r指针中指针指向元素较小的那个指针(向另一个指针所在的方向移动),再计算area,…,以此类推,然会最大的area

阅读全文 »

2.两数相加

题目描述

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

题目链接

思路

对应位置元素带进位相加

阅读全文 »

1.两数相加

题目描述

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。

题目链接

思路

1.暴力枚举法
枚举数组中的每一个数x,寻找数组中是否存在target-x
2.哈希表
改进了方法1中寻找数组中是否存在target-x的过程

阅读全文 »

python中的函数

python中的三种函数
1.函数:定义在模块中类之外的函数
示例:

def add(a, b):
    res = a + b
    return res

2.嵌套函数:定义在函数中的函数
示例:

def func1():
    def func2():
        pass
    ...

3.方法:定义在类中
示例:

class A(object):
    def _ _init_ _(self):   # 构造函数
        pass

    def a(self,...):   # 实例方法
        pass
    
    @classmethod
    def b(cls,...):  # 类方法
        pass

多线程下载图片

下面的代码是一个网络爬虫程序,可以定期下载图片。这个网络爬虫程序每隔一段时间都会执行一次下载图片任务,在下载任务完成后,休眠一段时间在执行。这样反复执行,知道爬虫程序停止。

示例代码:

# coding=utf-8

import time
import threading
import urllib.request as request

# 线程停止变量
isrunning = True


# 工作线程体函数
def workthread_body():
    while isrunning:
        # 线程开始工作
        print('工作线程执行下载任务...')
        download()
        # 线程休眠
        time.sleep(5)
    print('工作线程结束')


# 控制线程体函数
def controlthread_body():
    global isrunning
    while isrunning:
        # 从键盘输入停止指令exit
        command = input('请输入停止指令')
        if command == 'exit':
            isrunning = False
            print('控制线程结束。')


def download():
    url = 'https://victory-liao.github.io/images/avatar.jpg'
    req = request.Request(url)
    with request.urlopen(req) as response:
        data = response.read()
        f_name = 'download.jpg'
        with open(f_name, 'wb') as f:
            f.write(data)
            print('下载文件成功')


# 主线程
# 创建工作线程对象workthread
workthread = threading.Thread(target=workthread_body)
# 启动线程workthred
workthread.start()

# 创建控制线程对象controlthread
controlthread = threading.Thread(target=controlthread_body)
# 启动线程controlthread
controlthread.start()

线程停止

在线程体结束时,线程就停止了。但在某些业务比较复杂时,会在线程体重执行一个“死循环”。线程体是够执行“死循环”是通过
判断停止变量实现的,“死循环”结束则线程体结束,线程也就结束了。

示例代码:

# coding=utf-8

import time
import threading

# 线程停止变量
isrunning = True


# 工作线程体函数
def workthread_body():
    while isrunning:
        # 线程开始工作
        print('工作线程执行中...')
        # 线程休眠
        time.sleep(5)
    print('工作线程结束。')


# 控制线程体函数
def controlthread_body():
    global isrunning
    while isrunning:
        # 从键盘输入停止指令exit
        command = input('请输入停止指令:')
        if command == 'exit':
            isrunning = False
            print('控制线程结束')


# 主线程
# 创建工作线程对象workthread
workthread = threading.Thread(target=workthread_body)
# 启动线程workthread
workthread.start()

# 创建控制线程对象controlthread
controlthread = threading.Thread(target=controlthread_body)
# 启动线程controlthread
controlthread.start()

等待线程结束

等待线程结束: 一个线程(假设是主线程)需要等待另外一个线程(假设是t1子线程)执行结束才能继续执行。
实现: 通过调用join(timeout=None)方法
参数timeout用来设置超时时间,单位为秒。如果没有设置timeout,则可以一直等待,知道结束。

阅读全文 »

实现线程体的两种方式

实现线程体主要有以下两种方式:
1.自定义函数实现线程体
代码实例:

# coding=utf-8

import threading
import time


# 线程体函数
def thread_body():
    # 当前线程对象
    t = threading.current_thread()
    for n in range(5):
        # 当前线程名
        print('第{0}次执行线程{1}'.format(n, t.name))
        # 线程休眠
        time.sleep(2)
    print('线程{0}执行完成!'.format(t.name))


# 主线程
# 创建线程对象t1
t1 = threading.Thread(target=thread_body)
# 创建线程对象t2
t2 = threading.Thread(target=thread_body, name='MyThread')
# 启动线程t1
t1.start()
# 启动线程t2
t2.start()

2.自定义线程类实现线程体
代码实例:

# coding=utf-8

import time
import threading


class SmallThread(threading.Thread):
    def __init__(self, name=None):
        super().__init__(name=name)

    # 线程体函数
    def run(self):
        # 当前线程对象
        t = threading.current_thread()
        for n in range(5):
            # 当前线程名
            print('第{0}次执行线程{1}'.format(n, t.name))
            # 线程休眠
            time.sleep(2)
        print('线程{0}执行完成'.format(t.name))


# 主线程
# 创建线程对象t1
t1 = SmallThread()  # 通过自定义线程类,创建线程对象
# 创建线程对象t2
t2 = SmallThread(name='MyThread')
# 启动线程t1
t1.start()
# 启动线程t2
t2.start()

使用json提供的loads(str)函数进行JSON数据的解码

函数说明:
str - JSON字符串
返回值 - python数据
示例代码:

# coding=utf-8

import urllib.request
import json

# 使用json模块的loads(str)函数进行JSON数据的解码
url = 'http://localhost:8080/NoteWebService/note.do?action=query&ID=10'

req = urllib.request.Request(url)

with urllib.request.urlopen(req) as response:
    data = response.read()
    json_data = data.decode()
    print("JSON字符串:", json_data)

    py_dict = json.loads(json_data)  # 解码JSON字符串,返回字典
    print('备忘录ID:', py_dict['ID'])
    print('备忘录日期:', py_dict['CDate'])
    print('备忘录内容:', py_dict['Content'])
    print('用户ID:', py_dict['UserID'])