victory的博客

长安一片月,万户捣衣声

0%

SpringSecurity用户认证、授权、注销、权限控制、记住我、首页定制

  • 实现功能:授权不同的用户角色访问不同的模块,如下图所示:

  • 描述

    • 设置三个不同用户角色(victory,root,guest)
    • victory可以访问level2和leve3的内容,root可以访问页面的所有内容,guest只可以访问level1的内容,而且没有权限的模块在该用户登录时不显示。
    • 没有登录时,点击三个模块的内容会跳转到登录页面
    • 记住我功能
    • 首页定制(不使用SpringSecurity默认登录页面,使用自己写的登录页面)
  • 页面

  • 依赖导入

    • 导入thymeleaf依赖
      1
      2
      3
      4
      5
      6
      7
      8
      <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring5</artifactId>
      </dependency>
      <dependency>
      <groupId>org.thymeleaf.extras</groupId>
      <artifactId>thymeleaf-extras-java8time</artifactId>
      </dependency>
    • 导入Web依赖
      1
      2
      3
      4
      <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
    • 导入security依赖
      1
      2
      3
      4
      <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
  • 项目目录

  • 编写RootController映射请求(跳转页面)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RootController {
@RequestMapping({"/", "/index"})
public String index(){
return "index";
}

@RequestMapping("toLogin")
public String toLogin(){
return "views/login";
}

@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id){
return "views/level1/"+id;
}

@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id") int id){
return "views/level2/"+id;
}

@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id){
return "views/level3/"+id;
}
}
  • 编写SecurityConfig配置SpringSecurity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.example.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页只有对应有权限的人才能访问
//请求授权的规则
//链式编程
http.authorizeHttpRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");

//没有权限默认会跳到登录页面
http.formLogin();

//防止网站攻击 get不安全,可以使用post springboot默认开启csrf(注销失败可能的原因)
http.csrf().disable(); //关闭csrf功能

//注销,跳到首页
http.logout().logoutSuccessUrl("/");
}

//认证
//密码编码:PasswordEncoder
//在Spring Security 5.0+新增了很多加密方法
//报错 500 密码没有加密
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//这些数据正常应该从数据库中读
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("victory").password(new BCryptPasswordEncoder().encode("123")).roles("vip2", "vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
}
}
  • 权限控制(没有权限的模块在该用户登录时不显示)
    • 导入依赖
      1
      2
      3
      4
      5
      <dependency>
      <groupId>org.thymeleaf.extras</groupId>
      <artifactId>thymeleaf-extras-springsecurity4</artifactId>
      <version>3.0.4.RELEASE</version>
      </dependency>
    • 在页面中导入命名空间
      1
      <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    • 在页面中使用thymeleaf-security语法进行权限控制
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      <!DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
      <title>首页</title>
      <!--semantic-ui-->
      <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
      <link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
      </head>
      <body>

      <!--主容器-->
      <div class="ui container">

      <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
      <div class="ui secondary menu">
      <a class="item" th:href="@{/index}">首页</a>

      <!--登录注销-->
      <div class="right menu">
      <!--如果未登录-->
      <div sec:authorize="!isAuthenticated()">
      <a class="item" th:href="@{/toLogin}">
      <i class="address card icon"></i> 登录
      </a>
      </div>

      <!--如果登录:用户名和注销-->
      <div sec:authorize="isAuthenticated()">
      <a class="item">
      用户名:<span sec:authentication="name"></span>
      <!--角色:<span sec:authentication="principal.getUsername()"></span>-->
      </a>
      <a class="item" th:href="@{/logout}">
      <i class="sign-out icon"></i> 注销
      </a>
      </div>
      </div>
      </div>
      </div>

      <div class="ui segment" style="text-align: center">
      <h3>Spring Security Study by 秦疆</h3>
      </div>

      <div>
      <br>
      <div class="ui three column stackable grid">
      <!--根据用户的角色动态的实现-->
      <div class="column" sec:authorize="hasRole('vip1')">
      <div class="ui raised segment">
      <div class="ui">
      <div class="content">
      <h5 class="content">Level 1</h5>
      <hr>
      <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
      <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
      <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
      </div>
      </div>
      </div>
      </div>

      <div class="column" sec:authorize="hasRole('vip2')">
      <div class="ui raised segment">
      <div class="ui">
      <div class="content">
      <h5 class="content">Level 2</h5>
      <hr>
      <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
      <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
      <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
      </div>
      </div>
      </div>
      </div>

      <div class="column" sec:authorize="hasRole('vip3')">
      <div class="ui raised segment">
      <div class="ui">
      <div class="content">
      <h5 class="content">Level 3</h5>
      <hr>
      <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
      <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
      <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
      </div>
      </div>
      </div>
      </div>

      </div>
      </div>
      </div>
      <script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
      <script th:src="@{/qinjiang/js/semantic.min.js}"></script>
      </body>
      </html>
    • thymeleaf security整合可能出现的错误
      • thymeleaf security不生效,可以将SpringBoot版本降低到2.0.7.RELEASE
      • 登录后出现WhiteLabel Error Page,Html文件中关于thymeleaf-security的代码有错误
  • 记住我、首页定制
    • 首页定制、记住我
      在configure(HttpSecurity http)方法中添加以下代码即可定制首页
      1
      2
      3
      4
      //formLogin() 默认到登录页面(SpringSecurity自带登录页面)
      //usernameParameter("user") 与自定义登录页面用户名文本框的name属性对应
      //passwordParameter("pwd") 与自定义登录页面密码文本框的name属性对应
      http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
      在configure(HttpSecurity http)方法中添加以下代码即可实现记住我功能
      1
      2
      //开启记住我功能 cookie,默认保存两周
      http.rememberMe().rememberMeParameter("remember");
    • 页面
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      <!DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
      <title>登录</title>
      <!--semantic-ui-->
      <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
      </head>
      <body>

      <!--主容器-->
      <div class="ui container">

      <div class="ui segment">

      <div style="text-align: center">
      <h1 class="header">登录</h1>
      </div>

      <div class="ui placeholder segment">
      <div class="ui column very relaxed stackable grid">
      <div class="column">
      <div class="ui form">
      <form th:action="@{/login}" method="post">
      <div class="field">
      <label>Username</label>
      <div class="ui left icon input">
      <input type="text" placeholder="Username" name="user">
      <i class="user icon"></i>
      </div>
      </div>
      <div class="field">
      <label>Password</label>
      <div class="ui left icon input">
      <input type="password" name="pwd">
      <i class="lock icon"></i>
      </div>
      </div>
      <div class="field">
      <input type="checkbox" name="remember">记住我
      </div>
      <input type="submit" class="ui blue submit button"/>
      </form>
      </div>
      </div>
      </div>
      </div>

      <div style="text-align: center">
      <div class="ui label">
      </i>注册
      </div>
      <br><br>
      <small>blog.kuangstudy.com</small>
      </div>
      <div class="ui segment" style="text-align: center">
      <h3>Spring Security Study by 秦疆</h3>
      </div>
      </div>
      </div>

      <script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
      <script th:src="@{/qinjiang/js/semantic.min.js}"></script>
      </body>
      </html>

SpringBoot常用的请求映射方式注解

我们在处理web端应用的请求时,通常会使用如下几种方式进行请求映射,我们可以通过查看源码看到它们的真实面目。

  • @RequestMapping
源码对注解的注释:Annotation for mapping web requests onto methods in request-handling classes with flexible method signatures.

翻译:用于将web请求映射到具有灵活方法签名的请求处理类中的方法的注释。
  • @GetMapping
源码对注解的注释:Annotation for mapping HTTP GET requests onto specific handler methods.
Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

翻译:用于将HTTP GET请求映射到特定的请求处理方法的注释。具体来说,@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。

  • @PostMapping
源码对注解的注释:Annotation for mapping HTTP POST requests onto specific handler methods.
Specifically, @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST).

翻译:用于将HTTP POST请求映射到特定的请求处理方法的注释。具体来说,@PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。

  • @PutMapping
源码对注解的注释:Annotation for mapping HTTP PUT requests onto specific handler methods.
Specifically, @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT).

翻译:用于将HTTP PUT请求映射到特定的请求处理方法的注释。具体来说,@PutMapping是一个组合注解,是@RequestMapping(method = RequestMethod.PUT)的缩写。

  • @DeleteMapping
源码对注解的注释:Annotation for mapping HTTP DELETE requests onto specific handler methods.
Specifically, @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE).

翻译:用于将HTTP DELETE请求映射到特定的请求处理方法的注释。具体来说,@DeleteMapping是一个组合注解,是@RequestMapping(method = RequestMethod.DELETE)的缩写。

  • @PatchMapping
源码对注解的注释:Annotation for mapping HTTP PATCH requests onto specific handler methods.
Specifically, @PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH).

翻译:用于将HTTP PATCH请求映射到特定的请求处理方法的注释。具体来说,@PatchMapping是一个组合注解,是@RequestMapping(method = RequestMethod.PATCH)的缩写。

从源码注释和注解接口实现源代码可以得出以下结论:

  • 可以使用@RequestMapping注解并指定method属性对所有HTTP进行映射。
  • @XxxMapping注解是@RequestMapping(method=”XXX”)的缩写
    • @GetMapping是@RequestMapping(method = RequestMethod.GET)的缩写
    • @PostMapping是@RequestMapping(method = RequestMethod.POST)的缩写
    • @PutMapping是@RequestMapping(method = RequestMethod.PUT)的缩写
    • @DeleteMapping是@RequestMapping(method = RequestMethod.DELETE)的缩写
    • @PatchMapping是@RequestMapping(method = RequestMethod.PATCH)的缩写
  • 推荐用法:在对特定的请求进行映射时,采用对应的注解。

414.第三大的数

题目描述

给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。

  • 示例 1:
    输入:[3, 2, 1]
    输出:1
    解释:第三大的数是 1 。

  • 示例 2:
    输入:[1, 2]
    输出:2
    解释:第三大的数不存在, 所以返回最大的数 2 。

  • 示例 3:
    输入:[2, 2, 3, 1]
    输出:1
    解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
    此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。

题目链接

思路

  1. 排序
    将nums数组排序后,从数组末尾返回第三大的数。
  2. 有序集合
    遍历数组,同时用一个有序集合来维护数组中前三大的数。具体做法是每遍历一个数,就将其插入有序集合,若有序集合的大小超过 333,就删除集合中的最小元素。这样可以保证有序集合的大小至多为 333,且遍历结束后,若有序集合的大小为 333,其最小值就是数组中第三大的数;若有序集合的大小不足 333,那么就返回有序集合中的最大值。
  3. 一次遍历
    遍历数组,并用三个变量a、b、c来维护数组中的最大值、次大值和第三大值,在遍历过程中更新这三个值即可。

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    class Solution(object):
    def thirdMax(self, nums):
    """
    排序(自己实现快速排序)
    :type nums: List[int]
    :rtype: int
    """
    def quick_sort(arr, low, high):
    if low < high:
    pivot = partition(arr, low, high)
    quick_sort(arr, low, pivot - 1)
    quick_sort(arr, pivot + 1, high)

    def partition(arr, low, high):
    pivot_key = arr[low]
    while low < high:
    while low < high and arr[high] >= pivot_key:
    high -= 1
    arr[low], arr[high] = arr[high], arr[low]
    while low < high and arr[low] <= pivot_key:
    low += 1
    arr[low], arr[high] = arr[high], arr[low]
    return low

    quick_sort(nums, 0, len(nums) - 1)


    diff = 0
    for i in range(len(nums) - 1, -1, -1):
    if nums[i] != nums[i - 1]:
    diff += 1
    if diff == 2:
    return nums[i-1]

    return nums[-1]

    def thirdMax1(self, nums):
    """排序(直接调用排序方法)"""
    nums.sort(reverse=True)
    diff = 1
    for i in range(1, len(nums)):
    if nums[i] != nums[i-1]:
    diff += 1
    if diff == 3:
    return nums[i]
    return nums[0]

    def thirdMax2(self, nums):
    """有序集合"""
    from sortedcontainers import SortedList
    s = SortedList()
    for num in nums:
    if num not in s:
    s.add(num)
    if len(s) > 3:
    s.pop(0)
    return s[0] if len(s) == 3 else s[-1]

    def thirdMax3(self, nums):
    """一次遍历(用三个变量a,b,c来维护数组中的最大值、次大值和第三大值)"""
    a, b, c = float('-inf'), float('-inf'), float('-inf')

    for num in nums:
    if num > a:
    a, b, c = num, a, b
    elif a > num > b:
    b, c = num, b
    elif b > num > c:
    c = num

    return a if c == float('-inf') else c

    if __name__ == "__main__":
    slt = Solution()
    # third_max_num = slt.thirdMax([2, 2, 3, 1])
    # third_max_num = slt.thirdMax1([2, 2, 3, 1])
    # third_max_num = slt.thirdMax2([2, 2, 3, 1])
    third_max_num = slt.thirdMax3([2, 2, 3, 1])
    print(third_max_num)

python处理json数据

找出以下json数据中children键对应列表为空的data键的id值。
例如以下示例children键对应的列表为空时,返回data键的id值:

1
2
3
4
{
"data": {"id": 1234},
"children": []
}
  • 方法:
    分析数据可知,该文本数组为字典类型的嵌套,故可以使用递归的方法解决。
    首先全部输入文本就是一个大字典,因此递归函数输入为一个大字典,然后判断字典中children键对应的列表是否为空,
    如果为空则将children键对应的data键的id加入结果列表,如果children键对应的列表(列表中的元素仍为字典)不为空,
    则遍历列表中的字典,继续使用该递归函数进行处理,依次类推。
  • 重要的一步
    在处理json数据中极为重要的一步是将一个字符串表示的字典转换为python中的字典。
    我们可以使用python中的内置模块json中的loads方法将一个字符串表示的字典转换为json数据,既python中的字典。
    1
    json_data = json.loads(string_dict)
阅读全文 »

349.两个数组的交集

题目描述

给定两个数组 nums1 和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。

示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]

示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的

题目链接

思路

  1. 集合求交集
  2. 排序+双指针
    对nums1、nums2进行排序,设置两个指针index1、index2分别指向两个数组的头部,并按以下步骤进行:
    (1)如果元素相等则加入结果列表
    (2)如果index1指向的元素小于index2指向的元素,则index1指针后移,否则index2指针后移
    不断执行以上两个步骤,最后结果列表中的元素即为两个数字的交集。

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    """
    集合操作
    1.求交集
    set1.intersection(set2)
    2.求差集
    set1.difference(set2)
    3.求并集
    set1.union(set2)
    """


    class Solution(object):
    def intersection(self, nums1, nums2):
    """
    集合求交集
    :type nums1: List[int]
    :type nums2: List[int]
    :rtype: List[int]
    """
    return list(set(nums1).intersection(set(nums2)))

    def intersection1(self, nums1, nums2):
    """排序+双指针"""
    nums1.sort()
    nums2.sort()

    index1 = 0
    index2 = 0
    intersection = list()

    while index1 < len(nums1) and index2 < len(nums2):
    if nums1[index1] == nums2[index2]:
    if not intersection or nums1[index1] != intersection[-1]:
    intersection.append(nums1[index1])

    index1 += 1
    index2 += 1
    elif nums1[index1] < nums2[index2]:
    index1 += 1
    else:
    index2 += 1
    return intersection


    if __name__ == "__main__":
    slt = Solution()
    nums1 = [2, 1]
    nums2 = [1, 2]
    # inter = slt.intersection(nums1, nums2)
    inter = slt.intersection(nums1, nums2)
    print(inter)

268.丢失的数字

题目描述

给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。

示例 1:
输入:nums = [3,0,1]
输出:2
解释:n = 3,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 nums 中。

示例 2:
输入:nums = [0,1]
输出:2
解释:n = 2,因为有 2 个数字,所以所有的数字都在范围 [0,2] 内。2 是丢失的数字,因为它没有出现在 nums 中。

题目链接

思路

  1. 一次遍历
    遍历0~n的数字,如果不在nums数组中,则将其返回。
  2. 排序
    将数组排序之后,即可根据数组中每个下标处的元素是否和下标相等,得到丢失的数字。
    注:如果长度为n的数组(下标为0~n-1)元素与下标都相等,则丢失元素为n
  3. 位运算
    数组 nums 中有 n 个数,在这 n 个数的后面添加从 0 到 n 的每个整数,则添加了 n+1 个整数,共有 2n+1 个整数。
    在 2n+1 个整数中,丢失的数字只在后面 n+1 个整数中出现一次,其余的数字在前面 n 个整数中(即数组中)和后面 n+1 个整数中各出现一次,即其余的数字都出现了两次。
    根据出现的次数的奇偶性,可以使用按位异或运算得到丢失的数字。按位异或运算^满足交换律和结合律,且对任意整数 x 都满足 x^x=0 和 x^0=x。
    由于上述 2n+1 个整数中,丢失的数字出现了一次,其余的数字都出现了两次,因此对上述 2n+1 个整数进行按位异或运算,结果即为丢失的数字。
  4. 数学
    丢失的数字 = 0~n的和 - nums数组的和

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    class Solution(object):
    def missingNumber(self, nums):
    """
    一次遍历

    遍历0~n,如果数字不在nums中,就将它返回
    :type nums: List[int]
    :rtype: int
    """
    for i in range(len(nums) + 1):
    if i not in nums:
    return i

    def missingNumber1(self, nums):
    """
    将数组排序之后,即可根据数组中每个下标处的元素是否和下标相等,得到丢失的数字。

    注:如果长度为n的数组(下标为0~n-1)元素与下标都相等,则丢失元素为n
    """
    nums.sort()

    for i, num in enumerate(nums):
    if i != num:
    return i

    return len(nums)

    def missingNumber2(self, nums):
    """
    位运算
    """
    xor = 0

    for i, num in enumerate(nums):
    xor ^= i ^ num

    return xor ^ len(nums)

    def missingNumber3(self, nums):
    """
    数学运算
    """
    n = len(nums)

    total = (n*(n+1)) // 2
    nums_sum = sum(nums)

    return total - nums_sum


    if __name__ == "__main__":
    slt = Solution()
    nums = [3, 0, 1]
    # missing_number = slt.missingNumber(nums)
    # missing_number = slt.missingNumber1(nums)
    # missing_number = slt.missingNumber2(nums)
    missing_number = slt.missingNumber3(nums)
    print(missing_number)

文件操作

由于我在之前上传的博客文件(markdown文件)中使用了缩进表示代码块,这中方式显示的代码块不够美观,最近发现可以使用

来表示python代码块,以这种方式表示的代码块非常美观。但是我的博客中可能有上百篇需要去修改,因此考虑使用python自动化修改,这个过程需要使用文件操作方面的知识,因此又将python文件操作相关知识又练习了一遍,然后再抽出时间去修改博客文件代码块的表示方式。

注意: 在打开文件时,当mode选择’w+’,’a+’,’ab+’,’wb+’时,虽然官方文档说明这几种模式为可读可写,但是在使用这几种模式读文件时,读出内容为空,原因见以上示例中。

阅读全文 »

228.汇总区间

题目描述

给定一个 无重复元素 的 有序 整数数组 nums 。
返回数组中的连续区间范围列表。
列表中的每个区间范围 [a,b] 应该按如下格式输出:
“a->b” ,如果 a != b
“a” ,如果 a == b

示例 1:

1
2
3
4
5
6
输入:nums = [0,1,2,4,5,7]
输出:["0->2","4->5","7"]
解释:区间范围是:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

题目链接

思路

  1. 一次遍历
    我们从数组的位置 0 出发,向右遍历。每次遇到相邻元素之间的差值大于 1 时,我们就找到了一个区间。遍历完数组之后,就能得到一系列的区间的列表。
    在遍历过程中,维护下标 low 和 high 分别记录区间的起点和终点,对于任何区间都有 low≤high。当得到一个区间时,根据 low 和 high 的值生成区间的字符串表示。
    (1)当 low<high 时,区间的字符串表示为 “low→high”;
    (2)当 low=high 时,区间的字符串表示为 “low”。

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    class Solution(object):
    def summaryRanges(self, nums):
    """
    :type nums: List[int]
    :rtype: List[str]
    """
    if not nums:
    return []
    result = []
    temp_list = [nums[0]]
    for i in range(1, len(nums)):
    if nums[i] == nums[i - 1] + 1:
    temp_list.append(nums[i])
    else:
    if temp_list[0] == temp_list[-1]:
    result.append(str(temp_list[0]))
    else:
    result.append(str(temp_list[0]) + "->" + str(temp_list[-1]))
    temp_list = list()
    temp_list.append(nums[i])
    if temp_list:
    if temp_list[0] == temp_list[-1]:
    result.append(str(temp_list[0]))
    else:
    result.append(str(temp_list[0]) + "->" + str(temp_list[-1]))
    return result

    def summaryRanges1(self, nums):
    result = []
    i = 0
    n = len(nums)
    while i < n:
    low = i
    i += 1
    while i < n and nums[i] == nums[i - 1] + 1:
    i += 1
    high = i - 1
    temp = str(nums[low])
    if low < high:
    temp += "->"
    temp += str(nums[high])
    result.append(temp)
    return result

    if __name__ == "__main__":
    slt = Solution()
    nums = [0, 1, 2, 4, 5, 7]
    # nums = [0, 2, 3, 4, 6, 8, 9]
    # nums = []
    # result = slt.summaryRanges(nums)
    result = slt.summaryRanges1(nums)
    print(result)

219.存在重复元素2

题目描述

给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。

示例 1:
输入:nums = [1,2,3,1], k = 3
输出:true

示例 2:
输入:nums = [1,0,1,1], k = 1
输出:true

示例 3:
输入:nums = [1,2,3,1,2,3], k = 2
输出:false

题目链接

思路

  1. 哈希表
    使用哈希表存储每一个元素的最大下表,在遍历元素的过程中,如果该元素已存在于哈希表中,则判断该元素当前下标减去该元素的最大下标,如果差值小于k,则返回True;
    如果遍历过程中没有找到为相等元素且下标之差小于k的情况,则返回False。
  2. 滑动窗口
    数组 nums 中的每个长度不超过 k+1 的滑动窗口,同一个滑动窗口中的任意两个下标差的绝对值不超过 k。如果存在一个滑动窗口,其中有重复元素,则存在两个不同的下标 i 和 j 满足 nums[i]=nums[j] 且 ∣i−j∣≤k。如果所有滑动窗口中都没有重复元素,则不存在符合要求的下标。因此,只要遍历每个滑动窗口,判断滑动窗口中是否有重复元素即可。

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
    """
    超出时间限制
    :type nums: List[int]
    :type k: int
    :rtype: bool
    """
    dict1 = dict()
    for i in range(len(nums)):
    if nums[i] not in dict1.keys():
    dict1[nums[i]] = [i]
    else:
    dict1[nums[i]].append(i)

    for key in dict1.keys():
    for i in range(len(dict1[key])):
    for j in range(i+1, len(dict1[key])):
    if abs(dict1[key][i]-dict1[key][j]) <= k:
    return True
    else:
    return False

    def containsNearbyDuplicate1(self, nums, k):
    """超出时间限制"""
    i = 0
    while i < len(nums)-1:
    j = i + 1
    while j < len(nums):
    if nums[i] == nums[j] and abs(i-j) <= k:
    return True
    j += 1
    i += 1
    return False

    def containsNearbyDuplicate2(self, nums, k):
    """哈希表"""
    pos = {}
    for i, num in enumerate(nums):
    if num in pos and i - pos[num] <= k:
    return True
    pos[num] = i
    return False

    def containsNearbyDuplicate3(self, nums, k):
    """集合"""
    s = set()
    for i, num in enumerate(nums):
    if i > k:
    s.remove(nums[i - k - 1])
    if num in s:
    return True
    s.add(num)
    return False


    if __name__ == "__main__":
    slt = Solution()
    # print(slt.containsNearbyDuplicate1([1, 2, 3, 1], 3))
    # print(slt.containsNearbyDuplicate1([1, 0, 1, 1], 1))
    # print(slt.containsNearbyDuplicate1([1, 2, 3, 1, 2, 3], 2))
    # print(slt.containsNearbyDuplicate1([99, 99], 2))

    print(slt.containsNearbyDuplicate2([1, 2, 3, 1], 3))
    print(slt.containsNearbyDuplicate2([1, 0, 1, 1], 1))
    print(slt.containsNearbyDuplicate2([1, 2, 3, 1, 2, 3], 2))
    print(slt.containsNearbyDuplicate2([99, 99], 2))

217.存在重复元素

题目描述

给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。

示例 1:
输入:nums = [1,2,3,1]
输出:true

示例 2:
输入:nums = [1,2,3,4]
输出:false

题目链接

思路

  1. 遍历并统计
    遍历数组中的每一个数并统计这个数在数组中出现的次数,如果出现次数大于等于2,则返回True,
    ,如果正常结束,既遍历途中没有返回,则返回False
    注:超出时间限制!!!
  2. 集合
  3. 1 使用集合对nums数组进行去重,如果去重后的集合长度不等于数组的长度,则返回True,否则返回False
  4. 2 对于数组中每个元素,我们将它插入到集合中。如果插入一个元素时发现该元素已经存在于集合中,则说明存在重复的元素。
  5. 排序
    在对数字从小到大排序之后,数组的重复元素一定出现在相邻位置中。因此,我们可以扫描已排序的数组,每次判断相邻的两个元素是否相等,如果相等则说明存在重复的元素。

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    class Solution(object):
    def containsDuplicate(self, nums):
    """
    遍历并统计
    遍历数组中的每一个数并统计这个数在数组中出现的次数,如果出现次数大于等于2,则返回True,
    ,如果正常结束,既遍历途中没有返回,则返回False

    超出时间限制
    :type nums: List[int]
    :rtype: bool
    """
    for num in nums:
    if nums.count(num) >= 2:
    return True
    else:
    return False

    def containsDuplicate1(self, nums):
    """
    集合
    使用集合对nums数组进行去重,如果去重后的集合长度不等于数组的长度,则返回True,否则返回False
    """
    return len(set(nums)) != len(nums)

    def containsDuplicate2(self, nums):
    """
    排序
    在对数字从小到大排序之后,数组的重复元素一定出现在相邻位置中。因此,我们可以扫描已排序的数组,每次判断相邻的两个元素是否相等,如果相等则说明存在重复的元素。
    """
    nums.sort()
    for i in range(len(nums)-1):
    if nums[i] == nums[i+1]:
    return True
    else:
    return False

    def containsDuplicate3(self, nums):
    """
    集合
    对于数组中每个元素,我们将它插入到集合中。如果插入一个元素时发现该元素已经存在于集合中,则说明存在重复的元素。
    """
    hash_table = set()
    for num in nums:
    if num not in hash_table:
    hash_table.add(num)
    else:
    return True
    else:
    return False

    if __name__ == "__main__":
    slt = Solution()
    # result = slt.containsDuplicate([1, 2, 3, 1])
    # result = slt.containsDuplicate1([1, 2, 3, 1])
    # result = slt.containsDuplicate2([1, 2, 3, 1])
    result = slt.containsDuplicate3([1, 2, 3, 1])
    print(result)