leetcode算法题解(Java版)-3-广搜+HashMap

简介: 题目很简单,考到了一个知识点——异或:比较两个操作数的二进制的各个位置,相同则为0不同则为1。所以,1.与0异或是本身2.与和自己一样的异或是0.

一、运算符——异或"^"

题目描述

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

思路

  • 题目很简单,考到了一个知识点——异或:比较两个操作数的二进制的各个位置,相同则为0不同则为1。所以,1.与0异或是本身2.与和自己一样的异或是0.

代码

public class Solution {
    public int singleNumber(int[] A) {
        int res=0;
        for(int i=0;i<A.length;i++){
            res^=A[i];
        }
        return res;
    }
}

二、动态规划

题目描述

There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?

思路

  • 一开始看错题了,孩子们本来站好队了,我按权重从大到小排了一下。。。看了别人的代码,思路并不难:先给每人一个糖果,两个循环解决问题,一,从前往后扫一遍,如果下一个比上一个权重大就在上一个基础上加一;再从后往前扫一遍,如果前面的比后面的权重大且糖果比他少就再后面的基础上加一刷新原有的值。
  • 语法点:Arrays.fill(array,val);Arrays.sort(array);

代码

import java.util.Arrays;

public class Solution {
    public int candy(int[] ratings) {
        if(ratings==null||ratings.length==0){
            return 0;
        }
        int len=ratings.length;
        int [] cnt=new int [len];
        Arrays.fill(cnt,1);
        for(int i=1;i<len;i++){
            if(ratings[i]>ratings[i-1]){
                cnt[i]=cnt[i-1]+1;
            }
        }
        int sum=0;
        for(int i=len-1;i>0;i--){
            if(ratings[i-1]>ratings[i]&&cnt[i-1]<=cnt[i]){
                cnt[i-1]=cnt[i]+1;
            }
            sum+=cnt[i];
        }
        return sum+cnt[0];
    }
}

三、模拟题(环状)

题目描述

There are N gas stations along a circular route, where the amount of gas at station i isgas[i].
You have a car with an unlimited gas tank and it costscost[i]of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.

思路

  • 设置start和end,分别放在首尾。如果能继续走就让end++,不能则让start退一个。结束while循环有两种可能结果,一个是sum>=0,则最后相会的点就是出发点,另一个则不可能。

代码

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int len=gas.length;
        int start=len-1;
        int end=0;
        int sum=0;
        sum=gas[start]-cost[start];
        
        while(end<start){
            if(sum>=0){
                sum+=gas[end]-cost[end];
                end++;
            }
            else{
                start--;
                sum+=gas[start]-cost[start];
            }
        }
        return sum>=0?start:-1;
    }
}

四、BFS+HashMap

题目描述

Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors.

思路

  • 广搜,然后用map存储原来的和克隆的一一映射
  • HashMap中通过get()来获取value,通过put()来插入value,containsKey()则用来检验对象是否已经存在
  • Stack:st.push(node);st.pop();st.empty();

代码

/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */

import java.util.Stack;
import java.util.HashMap;

public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node==null){
            return null;
        }
        HashMap<UndirectedGraphNode,UndirectedGraphNode> map=new HashMap<>();
        Stack<UndirectedGraphNode> stackNode=new Stack<>();
        stackNode.push(node);
        while(!stackNode.empty()){
            UndirectedGraphNode tempNode=stackNode.pop();
            
            if(map.containsKey(tempNode)){
                continue;
            }
            UndirectedGraphNode copyNode=new UndirectedGraphNode(tempNode.label);
            
            for(UndirectedGraphNode uNode:tempNode.neighbors){
                copyNode.neighbors.add(uNode);
                if(map.containsKey(uNode)){
                    continue;
                }
                stackNode.push(uNode);
            }
            map.put(tempNode,copyNode);
        }
        return map.get(node);
    }
}
目录
相关文章
|
29天前
|
存储 算法 JavaScript
怎么刷算法,leetcode上有哪些经典题目
怎么刷算法,leetcode上有哪些经典题目
13 0
|
1月前
|
算法 搜索推荐 Java
数据结构与算法(Java篇)笔记--希尔排序
数据结构与算法(Java篇)笔记--希尔排序
|
7天前
|
算法 Java C语言
C++和Java中的随机函数你玩明白了吗?内附LeetCode470.rand7()爆改rand10()巨详细题解,带你打败LeetCode%99选手
C++和Java中的随机函数你玩明白了吗?内附LeetCode470.rand7()爆改rand10()巨详细题解,带你打败LeetCode%99选手
|
21天前
|
存储 算法 Java
Java数据结构与算法-java数据结构与算法(二)
Java数据结构与算法-java数据结构与算法
62 1
|
1天前
|
算法 DataX
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
|
6天前
|
Java 存储
键值之道:深入学习Java中强大的HashMap(二)
键值之道:深入学习Java中强大的HashMap
10 0
键值之道:深入学习Java中强大的HashMap(二)
|
16天前
|
搜索推荐 Java
Java排序算法
Java排序算法
18 0
|
16天前
|
搜索推荐 Java
Java基础(快速排序算法)
Java基础(快速排序算法)
22 4
|
19天前
|
存储 算法 JavaScript
Java入门高频考查算法逻辑基础知识3-编程篇(超详细18题1.8万字参考编程实现)
解决这类问题时,建议采取下面的步骤: 理解数学原理:确保你懂得基本的数学公式和法则,这对于制定解决方案至关重要。 优化算法:了解时间复杂度和空间复杂度,并寻找优化的机会。特别注意避免不必要的重复计算。 代码实践:多编写实践代码,并确保你的代码是高效、清晰且稳健的。 错误检查和测试:要为你的代码编写测试案例,测试标准的、边缘情况以及异常输入。 进行复杂问题简化:面对复杂的问题时,先尝试简化问题,然后逐步分析和解决。 沟通和解释:在编写代码的时候清晰地沟通你的思路,不仅要写出正确的代码,还要能向面试官解释你的
32 0
|
21天前
|
XML 存储 算法
Java数据结构与算法-java数据结构与算法(五)
Java数据结构与算法-java数据结构与算法
47 0