zoukankan      html  css  js  c++  java
  • find-all-numbers-disappeared-in-an-array

    https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/

    之前有一道题目:http://www.cnblogs.com/charlesblc/p/5998825.html "find-all-duplicates-in-an-array" 有一点类似。其中有很巧妙的解法,但是貌似在这里不能应用,现在还是用的轮换的方法。

    看到Discuss里面,有人用:出现一次就把该位置的数标记为负数,这样如果有一个位置还是正数,说明这个位置从来没出现过。但是,这种方法不能区分出现一次,还是多次。总的来说,这种方法的思路还是不错的,复用了位置上的数字来记录出现的次数(或者说出现与否,因为表达力有限,貌似只能区分有和没有两种)。

    package com.company;
    
    import java.util.*;
    
    class Solution {
        public List<Integer> findDisappearedNumbers(int[] nums) {
            for (int i=0; i<nums.length; i++) {
                int value = nums[i];
                int index = value - 1;
                nums[i] = 0;
                while (index >= 0 && nums[index] != value) {
                    //System.out.printf("1:i:%d, v:%d, nums[i]:%d
    ", index, value, nums[index]);
                    value = nums[index];
                    nums[index] = index + 1;
                    index = value - 1;
                    //System.out.printf("2:i:%d, v:%d
    ", index, value);
                }
            }
            List<Integer> ret = new ArrayList<>();
            for (int i=0; i<nums.length; i++) {
                if (nums[i] == 0) {
                    ret.add(i+1);
                }
            }
            return ret;
        }
    }
    
    public class Main {
    
        public static void main(String[] args) throws InterruptedException {
    
            System.out.println("Hello!");
            Solution solution = new Solution();
    
            int[] nums = {4,3,2,7,8,2,3,1};
            List<Integer> ret = solution.findDisappearedNumbers(nums);
            System.out.printf("Get ret: %d
    ", ret.size());
    
            Iterator<Integer> iter = ret.iterator();
            while (iter.hasNext()) {
                System.out.printf("%d,", iter.next());
            }
            System.out.println();
    
        }
    }
  • 相关阅读:
    UVALive 3664:Guess(贪心 Grade E)
    uva 1611:Crane(构造 Grade D)
    uva 177:Paper Folding(模拟 Grade D)
    UVALive 6514:Crusher’s Code(概率dp)
    uva 11491:Erasing and Winning(贪心)
    uva 1149:Bin Packing(贪心)
    uva 1442:Cave(贪心)
    学习 linux第一天
    字符编码问题
    orm 正向查询 反向查询
  • 原文地址:https://www.cnblogs.com/charlesblc/p/6019200.html
Copyright © 2011-2022 走看看