数组

2019-03-11  本文已影响0人  YOLO哈哈哈
1.Longest Consecutive Sequence(128. leetcode)
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 --;  } 
        }
    }

}
上一篇下一篇

猜你喜欢

热点阅读