簡體   English   中英

使用 java 挑戰問題在森林中查找和格式化視覺上美觀的樹木圖案

[英]Find and format visually aesthetically pleasant pattern of trees in a forest using java challenge question

最近面臨一個有上述問題的面試代碼挑戰。 有一個人擁有他的森林,樹木以行的形式種植。 每行都應以視覺上令人愉悅的方式包含一棵樹。 例如。 如上圖所示:

圖像1

圖2

上面的樹形圖案在視覺上永遠不會令人愉悅: image3

這里每列代表行中的樹及其高度。 沒有兩棵彼此相鄰的樹應該具有相同的高度,以使行在視覺上美觀。 農場主希望所有的樹木都具有視覺美感。 為此,他最多可以連續砍一棵樹。 找出可以連續切割一棵樹的方法數量,以使一排樹美觀。

即使某些行已經在視覺上美觀,然后返回 0 作為 function 的 output。

否則,即使在砍掉任何一棵樹之后,行也永遠無法形成視覺上美觀的圖案; 那么 function 應該返回 -1。

例如:A[] = {3, 4, 5, 3, 7}; 那么它可以通過 3 種方式在視覺上美觀:remove 3, A[] = {4, 5, 3, 7} else remove 4, A[] = {3, 5, 3, 7} else remove 5, A[ ] = {3, 4, 3, 7} 所以 function 應該返回 3。

G。 B[] = {1, 2, 3, 4, 2, 5}; 這種模式永遠不可能在視覺上美觀,所以 function 應該返回 -1。

例如。 c[] = {1, 3, 1, 2}; 這種模式在視覺上已經很美觀了,所以它應該返回 0。

我試圖解決它,如下一個解決方案部分所示。 有人可以建議使用 java 來解決問題以降低代碼復雜性和更快地工作的更好方法嗎?

下面是我的代碼。如果下面還有任何問題,請糾正我。

public int solution(int[] A) {

    int count = 0;
    List<Integer> arr = new ArrayList<Integer>();

    ArrayList<Integer> arrt = new ArrayList<Integer>();

    for (int i : A) {
        arr.add(i);
    }

    // first check if its already in correct sequence
    boolean check = false;
    for (int j = 0; j < A.length-2 ; j++) {
        if ((arr.get(j) - arr.get(j + 1) > 0) && (arr.get(j + 1) - arr.get(j + 2) < 0)) {
            check = true;
        } else if ((arr.get(j) - arr.get(j + 1) < 0) && (arr.get(j + 1) - arr.get(j + 2) > 0)) {
            check = true;
        } else {
            check = false;
            break;
        }
    }
    if (check) {
        return 0;
    }

    List<Integer> ab = new ArrayList<Integer>();

    for (int i = 0; i < A.length; i++) {
        ab.clear();
        ab.addAll(arr);
        ab.remove(i);
        int f = 0;
        boolean okay = false;
        while (f < A.length - 3) {
            if (!okay && f != 0) {
                break;
            }
            if ((ab.get(f) - ab.get(f + 1) > 0) && (ab.get(f + 1) - ab.get(f + 2) < 0)) {
                okay = true;
            } else if ((ab.get(f) - ab.get(f + 1) < 0) && (ab.get(f + 1) - ab.get(f + 2) > 0)) {
                okay = true;
            } else {
                okay = false;
            }
            f++;
        }
        if (okay) {
            count++;
        }
    }
    if (count == 0)
        count = -1;

    return count;
}

使用 Javascript

 const Solution = (A) => { let waysToCut = 0; if (isAsthetic(A)) { return 0; } for (let i = 0; i < A.length; i++) { let temp = [...A]; //making copy of [A] using spread operator (...) to prevent the actual array modifications temp.splice(i, 1); if (isAsthetic(temp)) { waysToCut += 1; } } if (waysToCut === 0) { return -1; } return waysToCut; }; const isAsthetic = (a) => { for (let i = 1; i < a.length; i++) { if ( (a[i] >= a[i - 1] && a[i] <= a[i + 1]) || (a[i] <= a[i - 1] && a[i] >= a[i + 1]) ) { return false; } } return true; };

Python 解決方案:

def solution(A):
  # Check if the given array is aesthatically pleasing
  check  = False
  for i in range(len(A)-2):
    if A[i] > A[i+1] and A[i+2] > A[i+1]:
      check = True
    elif A[i] < A[i+1] and A[i+2] < A[i+1]:
      check = True
    else:
      check = False
      break
      
  # If given array is aesthatically pleasing, return 0
  if check:
    return 0

  # Traverse again, Skipping element i -> and check if the new array is aesthatically pleasing

  count = 0
  for i in range(len(A)):
    arr = A[:i] + A[i+1:]
    i = 0
    check = False
    while i < len(A)-3:
      if not check and i != 0:
        break
      if arr[i] > arr[i+1] and arr[i+2] > arr[i+1]:
        check = True
      elif arr[i] < arr[i+1] and arr[i+2] < arr[i+1]:
        check = True
      else:
        check = False
      i+=1  
    if check:
      count+=1
  return -1 if not count else count
  
print(solution([3,4,5,3,7])) # TC: When A is not aesthatically pleasing but can be made by removing one element
print(solution([1,2,3,4,5])) # TC: When A cannot be made to be aesthatically pleasing
print(solution([1,4,1,4,1])) # TC: When A is already aesthatically pleasing

Output:

3
-1
0

這是我在 c 中的解決方案:

 #include <stdio.h>
        
    char aestheticallyPleasantCheck (int A[], int N) {
          int x;
          char pleasant = 0;
          for (x = 0; x < N - 2; x++){
                if ((A[x] < A[x + 1] && A[x + 1] > A[x + 2]) || (A[x] > A[x + 1] && A[x + 1] < A[x + 2])){
                    pleasant = 1;
                } else {
                    break;
                }
            }
            if (pleasant == 1 && x == N - 2) {
                return 0;
            } else {
                return 1;
            }
        }
        
        int solution (int A[], int N) {
          int count = 0;
          int ArrayCopy[N];
        
          if (aestheticallyPleasantCheck (A, N) == 0)
            {
              return 0;
            }
        
            for (int i = 0; i < N; i++){
                for (int m = 0; m < N; m++){
                    ArrayCopy[m] = A[m];
                }
            
                for (int m = i; m < N - 1; m++){
                    ArrayCopy[m] = ArrayCopy[m + 1];
                }
        
                if (aestheticallyPleasantCheck (ArrayCopy, N - 1) == 0){
                  count++;
                }
            }
        
            if (count == 0){
                count = -1;
            }
        
          return count;
        }
        
        
        /*
        Example test:   [3, 4, 5, 3, 7]
        Example test:   [1, 2, 3, 4]
        Example test:   [1, 3, 1, 2]
        */
        
        main ()
        {
        
          int A[] = { 3, 4, 5, 3, 7 };  // Expected 3 .^.^
          int B[] = { 1, 2, 3, 4 }; // 
          int C[] = { 1, 3, 1, 2 }; //
          int D[] = { 5, 3, 7, 8, 9 };
          printf ("Got %d : Expected 3\n", solution (A, sizeof (A) / sizeof (int)));
          printf("Got %d : Expected -1\n", solution( B, sizeof(B)/sizeof(int)));
          printf("Got %d : Expected 0\n", solution( C, sizeof(C)/sizeof(int)) );
          printf ("Got %d : Expected -1\n", solution (D, sizeof (D) / sizeof (int)));
          
          return 0;
        }

這是 java 中的簡短解決方案。

class Solution {
    public int solution(int[] A) {
        if (A.length < 3) {
            return A[0] != A[1] ? 0 : 1;
        }
        int count = 0;
        for (int i = 0; i < A.length - 2 ; i += 2) {
            int a = A[i];
            int b = A[i+1];
            int c = A[i + 2];
            if (!(a - b > 0 && b - c < 0) && !(a - b < 0 && b - c > 0)) {
                count ++;
            }
        }
        return count;
    }
}

這是我的解決方案。

class Solution {
    public int solution(int[] A) {
        // check if the input array in the correct order
        int count = 0;
        for(int i = 0; i < A.length - 2; i++) {
            if(A[i] < A[i+1]) {
                if(!(A[i+1] > A[i+2])) {
                    count++;
                }
            }
            else if(A[i] > A[i+1]) {
                if(!(A[i+1] < A[i+2]))  {
                    count++;
                }
            }
        }
        
        if(count == 0)
            return count;
        // if false then copy to Arraylist and do the removal
        List<Integer> inputArr = new ArrayList<Integer>();
        for(int item : A) {
            inputArr.add(item);
        }
        return doTheRemoval(inputArr);
    }

    private int doTheRemoval(List<Integer> inputArr) {
        int count = -1;
        for(int i = 0; i < inputArr.size(); i++) {
            // remove tree sequencely
            inputArr.remove(i);
            // check the rest
            for(int j = 0; j < inputArr.size() - 2; j++) {
                int a = inputArr.get(j);
                int b = inputArr.get(j + 1);
                int c = inputArr.get(j + 2);
                if((a - b < 0 && b - c > 0) || (a - b > 0 && b - c < 0)) {
                    if(count == -1) {
                        count = 0;
                    }
                    count++;
                }
            }
        }
        return count;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM