Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package other;
- public class interview_arrayshift_space {
- /**
- * n = 5
- * [1,2,3,4,5] or [5,4,3,2,1]
- * [1,2,3,4,5]: true
- * [3,4,5,1,2]: true
- * *[4,5,1,2,3]: true
- * [5,1,2,3,4]: true
- * [5,4,1,2,3]: false
- * *[3,2,1,5,4]: true
- *
- *
- * Time BigO: n * m
- * Space BigO: n
- *
- */
- public static void main (String[] args) {
- // int[] ary = {1,2,3,4,5};
- // int[] ary = {4,5,1,2,3};
- // int[] ary = {5,4,1,2,3}; // false
- // int[] ary = {4,5,6,7,8,1,2,3};
- // int[] ary = {7,8,4,5,6,1,2,3}; // wrong: double downs
- // int[] ary = {5,4,3,2,1};
- // int[] ary = {3,2,1,5,4};
- int[] ary = {7,6,5,4,3,2,1,9,8};
- // int[] ary = {3,2,1,7,6,5,9,8}; // wrong: double ups
- // append the exact same array to the end
- // int[] ary_2 = new int[ary.length * 2];
- // for (int i = 0; i < ary.length; i++) {
- // ary_2[i] = ary[i];
- // ary_2[i + ary.length] = ary[i];
- // }
- // ascending
- boolean is_asce_ok = check_asec(ary);
- System.out.println("is_asce_ok: " + is_asce_ok);
- // descending
- boolean is_desc_ok = check_desc(ary);
- System.out.println("is_desc_ok: " + is_desc_ok);
- }
- private static boolean check_asec(int[] ary) {
- int num_start_asec = 1;
- boolean isAsecOK = false;
- for (int i = 0; i < ary.length; i++) {
- // found starting number
- if (ary[i] == num_start_asec) {
- int i_ary_count = 0;
- int i_ary_tmp = i;
- while (true) {
- if (i_ary_count >= ary.length) {
- isAsecOK = true;
- break;
- }
- if (i_ary_tmp >= ary.length) {
- // % go around the array to the start
- i_ary_tmp = 0;
- };
- /** main logic here **/
- int val = i_ary_count + 1;
- if (ary[i_ary_tmp] != val) {
- isAsecOK = false;
- break;
- }
- i_ary_count++;
- i_ary_tmp++;
- }
- }
- if (isAsecOK) break;
- }
- return isAsecOK;
- }
- private static boolean check_desc(int[] ary) {
- int num_start_desc = ary.length;
- boolean isDescOK = false;
- for (int i = 0; i < ary.length; i++) {
- // found starting number
- if (ary[i] == num_start_desc) {
- int i_ary_count = 0;
- int i_ary_tmp = i;
- while (true) {
- if (i_ary_count >= ary.length) {
- isDescOK = true;
- break;
- }
- if (i_ary_tmp >= ary.length) {
- // % go around the array to the start
- i_ary_tmp = 0;
- };
- /** main logic here **/
- int val = num_start_desc - i_ary_count;
- if (ary[i_ary_tmp] != val) {
- isDescOK = false;
- break;
- }
- i_ary_count++;
- i_ary_tmp++;
- }
- }
- if (isDescOK) break;
- }
- return isDescOK;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement