Leetcode 967 Numbers With Same Consecutive Differences
阿新 • • 發佈:2019-01-01
Return all non-negative integers of length N
such that the absolute difference between every two consecutive digits is K
.
Note that every number in the answer must not have leading zeros except for the number 0
itself. For example, 01
0
is valid.
You may return the answer in any order.
Example 1:
Input: N = 3, K = 7 Output: [181,292,707,818,929] Explanation: Note that 070 is not a valid number, because it has leading zeroes.
Example 2:
Input: N = 2, K = 1 Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
Note:
1 <= N <= 9
0 <= K <= 9
這個題的意思是:N為數的位數,K為可以調整的數的大小
class Solution { public int[] numsSameConsecDiff(int N, int K) { if(N == 1){ return new int[]{0,1,2,3,4,5,6,7,8,9}; }//如果為1的話就是所有的個位數,注意0也包含在內 int array[] = new int[]{1,2,3,4,5,6,7,8,9};//1到9進行迴圈 for(int i = 2 ; i <= N;++i){//位數的迴圈 ArrayList<Integer> list = new ArrayList<>();//易於新增 for(int j : array){//調取array中的陣列 int y = j % 10;//抽取出個位數來 if(K + y < 10){ list.add(10 * j + y + K); }//加上K之後的數 if(y - K >= 0 && K != 0){ list.add(10 * j + y - K); }//減掉K之後的數 } array = list.stream().mapToInt(j->j).toArray();//將list中的數轉化為array中的數 } return array; } }
假如N=3,K=8,array中數字的變化:
1,2,3,4,5,6,7,8,9
19,80,91
191,808,919
其中程式碼中的list.stream().mapToInt().toArray()為Java8中的語法,其中stream是將list中的數變為資料流,mapToInt是將流轉化為list,其中的J->J是轉化的方式,就是1:1對映(如果為J->J*J則為平方的方式轉化),toArray是將之前轉化的數變為Array的形式。
以下附上Java8的文件:Java8