17.1 Write a function to swap a number in place (that is, without temporary variables). 这道题让我们交换两个数,但是不能用额外空间,那么我们可以先做差值,存入a中,然后再加上b,存入b中,那么此时的b即为原来的a,因为整个相当于做了一个a - b + b的过程,那么现在b是原来的a,而a中现在保存的是差值,,那么原来的b值就可以通过b-a来得到,保存到a中即可: 解法一: void swap(int a, i…
很多时候我要对List中的元素调换位置,这时候可以用如下代码,意思是将data中的index1与index2元素互换位置 //data 为List Collections.swap(data,index1,index2);…
Java中函数参数是按值传递的,在实现数组元素互换位置之前,我想先说一下Java函数参数传递过程.一般情况下我们会把参数分为基本数据类型和引用数据类型,然后分别来讲参数传递,因为他们的外在表现似乎是不同的,然而,他们的本质都是值传递.在讲值传递时,请务必将"实参的副本"这五个字刻在脑海,因为它是理解值传递的关键. // 例子1 int a = 0; void value(int x) { x = 1; } value(a); System.out.println(a); // 结果是…
18.4 Write a method to count the number of 2s between 0 and n. 这道题给了我们一个整数n,让我们求[0,n]区间内所有2出现的个数,比如如果n=20,那么满足题意的是2, 12, 20,那么返回3即可.LeetCode上有一道很类似的题Factorial Trailing Zeroes,但是那道题求5的个数还包括了因子中的5,比如10里面也有5,这是两题的不同之处.那么首先这题可以用brute force来解,我们对区间内的每一个数字…
17.14 Oh, no! You have just completed a lengthy document when you have an unfortunate Find/Replace mishap. You have accidentally removed all spaces, punctuation, and capitalization in the document. A sentence like "I reset the computer. It still didn…
17.11 Implement a method rand7() given rand5(). That is, given a method that generates a random number between 0 and 4 (inclusive), write a method that generates a random number between 0 and 6 (inclusive). 这道题说给了我们一个rand5()函数,可以生成0到4之间的随机数,让我们写一个函数r…
17.5 The Came of Master Mind is played as follows: The computer has four slots, and each slot will contain a ball that is red (R), yellow (Y), green (C) or blue (B). For example, the computer might have RGGB (Slot # 1 is red, Slots #2 and #3 are gree…
Oh, no! You have just completed a lengthy document when you have an unfortu- nate Find/Replace mishap. You have accidentally removed all spaces, punctuation, and capitalization in the document. A sentence like "I reset the computer. It still didn't b…
17.2 Design an algorithm to figure out if someone has won a game oftic-tac-toe. 这道题让我们判断玩家是否能赢井字棋游戏,有下面几点需要考虑: 1. 判断是否能赢hasWon函数是调用一次还是多次,如果是多次,我们可能为了优化而需要加入一些预处理. 2. 井字棋游戏通常是3x3的大小,我们是否想要实现NxN的大小? 3. 我们需要在代码紧凑,执行速度和代码清晰之间做出选择. #include <iostream> #…
17.13 Consider a simple node-like data structure called BiNode, which has pointers to two other nodes. The data structure BiNode could be used to represent both a binary tree (where nodel is the left node and node2 is the right node) or a doubly link…