注:题目来源于LintCode的Java/Python在线练习牛客网的在线编程练习KhanAcademy

 

题目1:

实现一个矩阵类Rectangle,包含如下的一些成员变量与函数:

两个共有的成员变量 width 和 height 分别代表宽度和高度。

一个构造函数,接受2个参数 width 和 height 来设定矩阵的宽度和高度。
一个成员函数 getArea,返回这个矩阵的面积。

#python
class
Rectangle: width = 0 height = 0 ''' * Define a constructor which expects two parameters width and height here. ''' def __init__(self, wid, hei): self.width = wid self.height = hei ''' * Define a public method `getArea` which can calculate the area of the * rectangle and return. ''' def getArea(self): return self.width*self.height
//C++
#include<iostream> using namespace std; class rectangle{ public: int width; int height; int area; rectangle(int, int); //构造函数 int getArea(); //计算面积 ~rectangle(); //析构函数 }; /* rectangle::rectangle(int wid = 0, int hei = 0){ //构造函数的定义 width = wid; height = hei; area = width*height; cout << "The object is being created." << endl; } */ //和上面是一样的效果 rectangle::rectangle(int wid = 0, int hei = 0): width(wid), height(hei), area(wid*hei){ cout << "The object is being created." << endl; } //根据第一种写法会出现错误提示,invalid use of unstatic-data member //int rectangle::getArea(int wid = width, int hei = height){ // area = hei*wid; // return area; //} int rectangle::getArea(){ //面积函数的定义 area = height*width; return area; } rectangle::~rectangle(){ cout<< "The object is being deleted." << endl; } int main(){ rectangle rec1; cout << "Please enter a integer as width: "; cin >> rec1.width; cout << endl << "Please enter a integer as height: "; cin >> rec1.height; cout << endl << "The area of this rectangle is " << rec1.getArea() << endl; return 0; }

 

题目2:

用binary search在排序好的序列中找到目标值。

伪代码:

1. Let min = 0 and max = n-1.
2. If max < min, then stop: target is not present in array. Return -1.
3. Compute guess as the average of max and min, rounded down (so that it is an integer).
4. If array[guess] equals target, then stop. You found it! Return guess.
5. If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
6. Otherwise, the guess was too high. Set max = guess - 1.
7. Go back to step 2.

Python:

import math
def doSearch(Array, Target):
    print("Searching...")
    minV = 0
    maxV = len(Array)-1
    while(maxV >= minV):
        guess = math.floor((minV + maxV)/2)
        print("guess:", guess, "Value", Array[guess])
        if(Array[guess] == Target): return guess
        elif(Target < Array[guess]): maxV = guess-1
        else: minV = guess+1
    return -1

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

result = doSearch(primes, 73)
print("Found prime at index ", result)

JavaScript:

/* Returns either the index of the location in the array,
  or -1 if the array did not contain the targetValue */
var doSearch = function(array, targetValue) {
    var min = 0;
    var max = array.length - 1;
    var guess;
    var num_guess = 0;
    while(max >= min){
       guess = floor((min+max)/2);
       //println(guess);
       //num_guess++;
       if(targetValue === array[guess]){
           //println(num_guess);
           return guess;
       } 
       else if(targetValue < array[guess]){max = guess-1;}
       else{min = guess+1;}
    }
    return -1;
};

var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 
        41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];

var result = doSearch(primes, 73);
println("Found prime at index " + result);

Program.assertEqual(doSearch(primes, 73), 20);

 

 

题目3:

给一组整数,按照升序排序,使用选择排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法(插入排序、快速排序、归并排序见(2))。

1)选择排序:

Algorithm:

1. Find the smallest card. Swap it with the first card.
2. Find the second-smallest card. Swap it with the second card.
3. Find the third-smallest card. Swap it with the third card.
4. Repeat finding the next-smallest card, and swapping it into the correct position until the array is sorted.

Python:

#!/usr/bin/python
def swap(Array, i, j):
    temp = Array[i];
    Array[i] = Array[j]
    Array[j] = temp

def indOfMin(Array, i):
    minInd = i
    for k in range(i,len(Array)):
        if Array[k] < Array[minInd]:
            minInd = k
    return minInd

def selectSort(Array):
    for i in range(len(Array)):
        minInd = indOfMin(Array, i)
        if minInd != i:
            swap(Array, i, minInd)

testArray = [10, 2, 4, 2, 1, 5, 9, 7, 8]
selectSort(testArray)
print(testArray)

 

C++:

在C++中,strlen(str) == str.length() == str.size(),求数组长度。这里用sizeof(array)/sizeof(array[0])间接通过数组占用空间和单元素占用空间的比来计算数组长度。

但数组作为函数参数传入时,传入的仅仅是一个指针,所以要用到数组长度的时候,也需要作为一个参数传入。

#include <iostream>
using namespace std;

//交换
void swap(int Array[], int i, int j){
    int temp = Array[i];
    Array[i] = Array[j];
    Array[j] = temp;
}
//找最小值的下标
int indexOfMin(int Array[], int len, int i){  //必须传入数组长度,Array[]只是传入一个指针
    int minIndex = i;
    for(int k = i; k < len; k++){
        if(Array[k] < Array[minIndex]) {minIndex = k;}
    }
    return minIndex;
}
//排序
void SelectionSort(int Array[], int len){  //必须传入数组长度,Array[]只是传入一个指针
    int minInd = 0;
    for(int i = 0; i < len; i++){
        minInd = indexOfMin(Array, len, i);
        if(i != minInd) swap(Array, i, minInd);
    }
}
int main()
{
    int testArray[] = {10, 2, 4, 2, 1, 5, 9, 7, 8};
    SelectionSort(testArray, sizeof(testArray)/sizeof(testArray[0]));
    cout << "The length of the array is " << sizeof(testArray)/sizeof(testArray[0]) << "." << endl;
    cout << "The sorted elements:" << endl;
    for(int i = 0; i < sizeof(testArray)/sizeof(testArray[0]); i++){
        cout << *(testArray+i) << endl;
    }
    return 0;
}

 

Javascript:

 

var swap = function(array, firstIndex, secondIndex) {
    var temp = array[firstIndex];
    array[firstIndex] = array[secondIndex];
    array[secondIndex] = temp;
};

var indexOfMinimum = function(array, startIndex) {

    var minValue = array[startIndex];
    var minIndex = startIndex;

    for(var i = minIndex + 1; i < array.length; i++) {
        if(array[i] < minValue) {
            minIndex = i;
            minValue = array[i];
        }
    } 
    return minIndex;
}; 

var selectionSort = function(array) {
    var k =0;
    for(var i = 0; i < array.length; i++){
        k = indexOfMinimum(array, i);
        swap(array, k, i);
    }
};

 

posted on 2017-11-21 18:20  RRRRecord  阅读(623)  评论(0编辑  收藏  举报