Facebook面试题 这是一个编程题,动手做做才会有体会。给一个数组和一个值,从数组中删除这个指定的值的所有出现,并且返回新的数组的长度。size_t remove_elem(T* array, size_t len, T elem) {}。
题目地址 新浪微博 @陈利人 http://weibo.com/1915548291/z24j5a6VP
#include "gtest/gtest.h"
template <typename T, size_t N>
char (&ArraySizeHelper(const T (&array)[N]))[N];
#define arraysize(array) (sizeof(ArraySizeHelper(array)))
//Caller's responsibility to pass appropriate arguments.
template<typename T>
size_t RemoveElement(T elements[],const size_t size, const T key)
{
size_t where_to_place= 0;
for(size_t i=0; i< size; i++)
if(elements[i]!= key)
elements[where_to_place++]= elements[i];
return where_to_place;
}
template<typename T>
bool CompareNativeArray(const T a[],const T b[],const size_t size)
{
for(size_t i= 0; i<size; i++)
if(a[i]!= b[i])
return false;
return true;
}
TEST(RemoveElementTest, Case1) {
int input[]= {1,1,2,3,4,1,8,6,1,1};
int result[]= {2,3,4,8,6};
int new_size= RemoveElement<int>(input, arraysize(input), 1);
ASSERT_EQ(new_size, arraysize(result));
ASSERT_TRUE(CompareNativeArray<int>(input, result,new_size));
}
TEST(RemoveElementTest, Case2) {
int input[]= {1,1,1,1,1,1,1,1,1};
int new_size= RemoveElement<int>(input, arraysize(input), 1);
ASSERT_EQ(new_size, 0);
}
TEST(RemoveElementTest, Case3) {
int input[]= {1,1,1,1,1,1,2,2,2,2,2,2};
int result[]= {2,2,2,2,2,2};
int new_size= RemoveElement<int>(input, arraysize(input), 1);
ASSERT_EQ(new_size, arraysize(result));
ASSERT_TRUE(CompareNativeArray<int>(input, result,new_size));
}
TEST(RemoveElementTest, Case4) {
int input[]= {1,2,1,2,1,2};
int result[]= {2,2,2};
int new_size= RemoveElement<int>(input, arraysize(input), 1);
ASSERT_EQ(new_size, arraysize(result));
ASSERT_TRUE(CompareNativeArray<int>(input, result,new_size));
}
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}