zoukankan      html  css  js  c++  java
  • <Array> 41 134

    41. First Missing Positive

    思路是把1放在数组第一个位置 nums[0],2放在第二个位置 nums[1],即需要把 nums[i] 放在 nums[nums[i] - 1]上,遍历整个数组,如果 nums[i] != i + 1, 而 nums[i] 为整数且不大于n,另外 nums[i] 不等于 nums[nums[i] - 1] 的话,将两者位置调换,如果不满足上述条件直接跳过,最后再遍历一遍数组,如果对应位置上的数不正确则返回正确的数

    class Solution {
        public int firstMissingPositive(int[] nums) {
            int n = nums.length;
            for(int i = 0; i < n; i++){
                while(nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]){
                    swap(nums, nums[i] - 1, i);
                }
            }
            for(int i = 0; i < n; i++){
                if(nums[i] != i + 1) return i + 1;
            }
            return n + 1;
        }
        
        public void swap(int[] a, int i, int j){
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }

    134. Gas Station

    如果当前起点油量小于0,说明从0开始的任何一个点都不能作为起点,此时start + 1。

    最后如果total总油量小于等于0,则说明不满足条件。

    class Solution {
        public int canCompleteCircuit(int[] gas, int[] cost) {
            if(gas == null || cost == null || gas.length == 0 || cost.length == 0) return -1;
            
            int total = 0;
            int cur = 0;
            int start = 0;
            
            for(int i = 0; i < cost.length; i++){
                cur += gas[i] - cost[i];
                
                if(cur < 0){
                    start = i + 1;
                    cur = 0;
                }
                
                total += gas[i] - cost[i];
            }
            return total >= 0 ? start : -1;
        }
    }
  • 相关阅读:
    Autofs
    markdown 基本语法
    Why Linux Doesn’t Need Defragmenting
    How to reconfigure installed dpkg package (tzdata, locales)
    weblogic性能监控
    exec
    在Oracle中查询表的大小
    hadoop主要概念的理解和学习
    ORACLE ASM中查询表空间使用情况、数据文件路径、裸设备磁盘总大小剩余大小
    linux 查看内存和cpu占用比较多的进程
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11872209.html
Copyright © 2011-2022 走看看