NO.7
今天參加了愛奇藝的筆試,來分享一下編程題,就是很簡單的兩道題:
1.在一個字符串中找到第一個出現一次的字符,並返回ascii 碼
public class main {
public static char firstOne(String s)
{
int result = 0;
char temp;
int[] num = new int[52];
for (int i = 0; i < s.length(); i ++)
{
temp = s.charAt(i);
if ( temp >= 'a' && temp <= 'z' )
{
num[temp - 'a']++;
}
else
if (temp >= 'A' && temp <= 'Z')
{
num[temp - 'A' + 26] ++;
}
}
for (int i = 0; i < num.length; i ++)
{
if (num[i] == 1)
{
if (i >= 0 && i <=26)
{
result = i+97;
}
else
result = i+65-26;
break;
}
}
return result;
}
}
大概形式和上面的差不多,只要進行修改一下便可
2.n個人圍成一圈,按順序排序,從第一個人開始報數,報到3 的人退出最後留下的第幾號
public static int main(String[] args) {
int n = 0 ;
Scanner input = new Scanner(System.in);
int p = input.nextInt();
/**** 初始化人員 ***/
boolean[] per = new boolean[p];
for (int i = 0; i < per.length; i++) {
per[i] = true;
}
int t = 0, len = per.length;
while (len > 1) {
for (int i = 0; i < per.length; i++) {
if (per[i]) {
t++;
if (t == 3) {
t = 0;
per[i] = false;
len--;
}
}
}
}
for (int i = 0; i < per.length; i++) {
if (per[i]) {
n = i ;
}
}
return n;
}
今天做得額外的一道經典算法題:
大概意思就是,把二叉查找樹轉換成雙向鏈表
#include <stdio.h>
#include <stdlib.h>
struct BSTreeNode {
int value;
struct BSTreeNode *left;
struct BSTreeNode *right;
};
void Convert( struct BSTreeNode * head, struct BSTreeNode * tail, struct BSTreeNode *root ) {
struct BSTreeNode * left,* right;
if ( root == NULL ) {
head = NULL;
tail = NULL;
return;
}
Convert( head, tail , root->left );
Convert(head, tail , root->right );
if ( left != NULL ) {
left->right = root;
root->left = left;
}
else {
head = root;
}
if ( right != NULL) {
root->right = right;
right->left = root;
}
else {
tail = root;
}
}
struct BSTreeNode *treeTolinkedList( struct BSTreeNode *root ) {
struct BSTreeNode *head,*tail;
Convert( head , tail , root );
return head;
}
struct BSTreeNode *CreatBSTree() {
int data;
struct BSTreeNode *tree;
scanf("%d " , &data );
if (data == -1 ) {
return NULL;
}
else {
tree = ( struct BSTreeNode *)malloc( sizeof(struct BSTreeNode ) ) ;
tree->value = data;
tree->right = CreatBSTree();
tree->left = CreatBSTree();
return tree;
}
}
void InOrderTraverse( struct BSTreeNode *root ) {
if (root->left) {
InOrderTraverse(root->left );
}
if (root) {
printf("%d", root->value ) ;
}
if ( root->right ) {
InOrderTraverse(root->right );
}
}
int main () {
struct BSTreeNode *root = CreatBSTree();
InOrderTraverse(root);
printf("\n");
struct BSTreeNode *head = treeTolinkedList( root );
struct BSTreeNode *temp = head;
while ( temp != NULL ) {
printf( "%d", temp->value );
temp = temp->right;
}
getchar();
return 0;
}