数组

作者: YOLO哈哈哈 | 来源:发表于2019-03-11 04:04 被阅读0次
    1.Longest Consecutive Sequence(128. leetcode)
    • 这道题 利用了 HashMap 的数据结构, 把 element 作为key , 存在了 hashmap 中. value 存 左边+ 右边+ 1 的值
    • HashMap 的作用: 去重 + 快速找到 element
    public int longestConsecutive(int[] nums) {
    int res = 0;
    Map<Integer, Integer> map = new HashMap<>();
    for(int n : nums){
        if( !map.containsKey( n )){
            int left = map.continsKey( n - 1) ? map.get(n - 1): 0;
            int right = map.containsKey( n + 1) ? map.get( n + 1): 0;
            sum  = left + right + 1;
            map.put(n, sum);
            res = res > sum ? res : sum;
            map.put( n - left , sum);
            map.put( n + right , sum);
        }else{
            continue;
        }
    }
    return res;
    }
    
    2.Diagonal Traverse(498. leetcode)
    public int[] findDiagonalOrder(int[][] matrix) {
        if(matrix.length == 0) return new int[0];
        int r = 0, c = 0, m = matrix.length , n = matrix[0].length , int[] arr = new int[m * n];
        for( int i =0; i<arr.length ; i++){
            if( ( r + c) % 2 == 0){ /* moving up*/
                if( c == n -1) r --;
                else if ( r ==  0 ) c ++ ;
                else { r -- ; c ++ ;}
            }else{ /* moving down */
                if( r == m -1) c ++;
                else if( c == 0) r --;
                else{ r ++ ; c --;  } 
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:数组

          本文链接:https://www.haomeiwen.com/subject/xdimpqtx.html