首页 > 其他 > 详细

MultiDimArray

时间:2017-12-03 10:33:30      阅读:213      评论:0      收藏:0      [点我收藏+]
code 不难,multi dimension array 的求 summation。 之前准备地里的LinkedIn高频题一个没碰到。。。

/** Suppose you are given a class that implements a k-dimensional array 
* interface and you want to perform an operation that requires you to 
* iterate over all elements of the array using its indices. To be 
* specific, let‘s assume we want to calculate the sum of all elements in 
* the array. The interface only provides you a get(int[]) method which 鏉ユ簮涓€浜?.涓夊垎鍦拌鍧?. 
* allows one to fetch the element at that location given the indices along
* each dimension.
* 
* For e.g, suppose we are dealing with 4D arrays, given [2, 1, 3, 0], the 
* class will provide you array[2][1][3][0].
*
* Write a function that given an instance of the k-D array class and size . 1point 3acres 璁哄潧
* of its dimensions, calculates the sum of all elements.
*
* @param instance of MultiDimArray class that implements a k-D array of 
*        ints which provides a method x.get(int[]) to get the element
*        located at the indices in the array. from: 1point3acres.com/bbs 
* @param array of ints stating the size of each dimension of the k-D array. 鍥磋鎴戜滑@1point 3 acres
* @return an int which is the sum of all elements in the k-D array
*
* example: Given object m that holds a 2x2x3 array 
* a=[[[3, 2, 2], [1, 5, 0]], [[2, 0, 1], [1, 1, -2]]] (Only for illustration
* purposes. This need not be the internal implementation of our k-D array) 
* the function call arraySum(m, [2, 2, 3]) should return 16 
* (=3+2+2+1+5+2+1+1+1-2)
*/

/* DO NOT IMPLEMENT */
public interface MultiDimArray {
    int get(vector<int> indices);
}


public int arraySum (MultiDimArrayImpl m, int [] dimensions) {
}

 

public List<int[]> getAllIndex (int[] dimensions) {
                List<int[]> result = new ArrayList<int[]>();
                int[] index = new int[dimensions.length];
                helper(result, index, 0, dimensions);
                return result;. 
        }
       
        private void helper(List<int[]> result, int[] index, int depth, int[] dimensions) {
                if (depth == dimensions.length) {-google 1point3acres
                        result.add(index.clone());
                        return;
                }
                int currentDimension = dimensions[depth];
                for (int i=0; i<currentDimension; i++) {
                        index[depth] = i;-google 1point3acres
                        helper(result, index, depth+1, dimensions);
                }
        }

  

MultiDimArray

原文:http://www.cnblogs.com/apanda009/p/7964875.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!