Some data structure ideas (1) and data structure ideas

Source: Internet
Author: User
Tags stack pop

Some data structure ideas (1) and data structure ideas

Find the maximum k value of a single-chain table

At the beginning, I thought of a stupid method. First, I traverse a single-chain table, calculate the length of the single-chain table len, and then traverse the single-chain table from the beginning to the len-k node, this node is the last k node of a single-chain table. However, the time complexity of this algorithm is quite high. Another simpler method is:Set two pointers, pointing to the first node of the single-chain table respectively, and then let one pointer go k steps first, and then let the two pointers go at the same time, until the first pointer reaches the end of the single-linked table.

Java Word Segmentation

Lucene http://www.cnblogs.com/zuoxiaolong/p/lang2.html

Php Word Segmentation

A dedicated library http://www.cnblogs.com/xshang/p/3603037.html

Determines whether a linked list is a circular linked list.

Algorithm idea: when creating a circular linked list, set two pointers, head pointer and tail pointer, head and tail so that tail-> next = head, that is, let the tail node point to the header node, the tail insertion method is used when the node is created. Each time a new node is directed to the next node of the last node, the next node of the first node is directed to the new node, then assign the new node value to the first and last nodes.

When determining whether it is a circular linked list, we also set two pointers, slow pointer and fast pointer, so that the fast pointer moves twice each time than the slow pointer. If the fast pointer catches up with the slow pointer, It is a circular linked list; otherwise it is not a circular linked list. If the fast pointer or slow Pointer Points to NULL, it is not a circular linked list.

There is a single-chain table, where there may be a ring, that is, the next of a node points to the previous node in the linked list, so that a ring is formed at the end of the linked list.

Problem:

1. How to determine whether a linked list is such a linked list? 2. If the linked list shows an existing ring, what if the entry point of the ring is found?

1. Determine whether the linked list has a ring. The method is as follows:

Set two pointers (fast and slow). The initial values all point to the header. slow moves one step forward each time, and fast moves two steps forward each time. If the linked list has a ring, fast must first enter the ring, when slow enters the ring, the two pointers must meet each other. (Of course, if the first line to the end of fast is NULL, it is a non-circular linked list ).

2. Find the entry point of the ring:

When fast encounters slow, slow certainly does not traverse the linked list, and fast already loops n circles (1 <= n) in the ring ). Assume that slow takes the s step, then fast takes 2 s step (the number of fast steps is equal to the number of s plus n turns on the ring), set the ring length to r, then:

2 s = s + nr

S = nr

Set the length of the entire linked list to L. The distance between the entrance ring and the encounter point is x, and the distance from the start point to the entrance point is.

A + x = nr

A + x = (n-1) r + r = (n-1) r + L-

A = (n-1) r + (L-a-x)

(L-a-x) is the distance from the encounter point to the ring entry point,From the head of the linked list to the entry point of the ring is equal to (n-1) the inner ring of the loop + the encounter point to the inner point of the ring, so we set a pointer from the head of the linked list and the encounter point, each taking a step, the two pointers must meet, and the first point of the encounter is the ring entry point.

Determines whether two single-chain tables are intersecting. If yes, the first vertex of the intersection is given (both linked lists do not have loops ).

1. Connect one of the linked lists to the beginning and end, and check whether the other linked list has a ring. If so, the two linked lists are intersecting, and the detected dependency ring entry is the first vertex of the intersection.

2. If the two linked lists intersect, the two linked lists are the same nodes from the intersection to the end of the linked list, we can traverse one linked list first until the end, and then traverse another linked list, if you can also go to the same end point, the two linked lists will intersection.

Now let's write down the length of the two linked lists and traverse them again. The long chain table node starts to step forward (lengthMax-lengthMin), and then the two linked lists move forward simultaneously, each step, the first point of an encounter is the first point of the intersection of two linked lists.

Except one or two or three numbers in an integer array, other numbers appear twice. Write a program to find the numbers that appear only once. The time complexity is O (n) and the space complexity is O (1)

  • If only one occurrence occurs, the nature of the exclusive or is investigated,That is, if the same number and the active result of self-exclusive or is zero, then the array will be traversed cyclically and all elements in the array will be subjected to an exclusive or operation, the two numbers are all different or different, and the result is the number that appears only once.
  • If two numbers appear only once, set them to a and B. The same is true for applications,But the result x = a ^ B for all array elements is exclusive or, because a and B are different numbers, x is certainly not 0. For x, from the low position to the high position, find the first bit to 1 and set it to the m bit. The bit of the m bit must come from a or B, it is impossible for both a and B to have 1 m bit (from low to high. In this way, the array can be divided into two parts based on the m-bit. One group is 0, and the other group is 1. in this way, the problem is decomposed into numbers that only appear once in two arrays.
  • Consider that three numbers appear once in the given array, which is slightly more complex than the two. Perform step-by-step analysis and set these three numbers to a, B, and c:

(1) returns x = a ^ B ^ c, but x is not one of a, B, and c. Assume that x is, B ^ c = 0 indicates B = c, which is in conflict with the conditions given by the question.

(2) set f (n) to the position where the first bit is 1 starting from the low position in step 2. f (x ^ ), f (x ^ B), f (x ^ c) certainly do not get 0, because x ^ a, x ^ B, x ^ citself is not 0. F (x ^ a) ^ f (x ^ B) ^ f (x ^ c) is not 0. Because the result of f (x ^ a) ^ f (x ^ B) may be 0, or two bits may be 1. Assume that the position where the result bit of f (x ^ c) is 1 overlaps with one of f (x ^ a) ^ f (x ^ B, then, f (x ^ a) ^ f (x ^ B) ^ f (x ^ c) Only one bit is 1, if not, three bits are 1.

(3) it can be inferred that at least one bit in f (x ^ a) ^ f (x ^ B) ^ f (x ^ c) is 1. Assume that the mbit bit from low to high is 1. so we can draw a conclusion that one or three of x ^ a, x ^ B, and x ^ c have 1 (there cannot be two, because there are two, returns 0 ).

(4) it is proved that x ^ a, x ^ B, and x ^ c only have the first m-bit of 1. assume that their nth m bit is 1, then the nth m bit of x is 0, but x = a ^ B ^ c, and its nth m bit must be 1. Therefore, this assumption is not true. On the contrary, assume that the m-bit of x is 1, a, B, and c are both 0, which is not true because x = a ^ B ^ c. Therefore, in summary, x ^ a, x ^ B, and x ^ c have only one m bit of 1. This problem can be easily solved. Find the first number that appears only once Based on the MTH bit.

Returns the specified English string.

Double pointer, one at the beginning, one at the end, and then change the content.

For example, I love programming. The result is:. gnimmargorp evol I. The core code is as follows:

#include<stdio.h>  #include<string.h>    void swap_string(char *p_start, char *p_end) {      char temp;      while(p_start <= p_end) {          temp = *p_start;          *p_start = *p_end;          *p_end = temp;          p_start++;          p_end--;      }  }    void main() {      char str[] = "I love programming.";      swap_string(str, str + strlen(str) - 1);      printf("%s\n", str);  }

Given a string, for example, "test **", requires extra characters other than letters 

This also requiresSet two pointers, one slow pointer and one fast pointer. If the fast Pointer Points to a letter, assign the value to the slow pointer. Otherwise, the fast pointer continues to move forward.The core code is as follows:

#include<stdio.h>  #include<string.h>    void trim_word(char *word) {      char *p_slow = word;      char *p_fast = word;      while(*p_fast) {          if(!(*p_fast >= 'a' && *p_fast <= 'z') && !(*p_fast >= 'A' && *p_fast <= 'Z')) {              p_fast++;          } else {              *p_slow++ = *p_fast++;          }      }      *p_slow = '\0';  }  void main() {      char word[] = "   test **   ";      trim_word(word);      printf("%s\n", word);  }

Specify a string, for example, "abccba", to determine whether it is a forward message.

Array can be applied, but the index speed of the array is not as fast as the pointer, soSet two pointers, one pointing to the start of the string, and the other pointing to the end of the string to move synchronously.The core code is as follows:

#include<stdio.h>  #include<string.h>    int is_palindrome(char *str) {      char *p_start = str;      char *p_end = str + strlen(word) - 1;      while(p_start < p_end) {          if(*p_start != *p_end) {              return 0;          }          p_start++;          p_end--;      }      return 1;  }  void main() {      char string[] = "abccba";      if(is_palindrome(string)) {          printf("string is palindrome.\n");      } else {          printf("string is not palindrome.\n");      }  }

Given an ordered array, and then given a number m, find two numbers in the array so that the sum of the two numbers is equal to m.

#include<stdio.h>    #include<stdlib.h>     void FindTwoNumbers(int a[], int n, int dest)  {        int *e, *f;        e = a;        f = a + n - 1;        int sum;        sum = *e + *f;        while(sum != dest && e < f)        {            if(sum < dest) {                sum = sum - *e + *(++e);           } else {                 sum = sum - *f + *(--f);          }      }        if(sum == dest) {            printf("%d=%d+%d\n",dest,*e,*f);      } else {          printf("not find\n");      }  }      void main()    {         int num[] = {1, 2, 4, 7, 11, 15};        int temp = 9;        FindTwoNumbers(num, sizeof(num)/sizeof(int), temp);    }

String shifting

This is the string shift problem. This is also used as a double pointer. Assume that the given string "abcdefg" is used to move the string three digits to the left. The result is: "defgabc". How can this problem be solved,First, find the demarcation point and divide the string into two parts. The natural demarcation point should be related to the number of moving digits. Therefore, divide the string into two parts: abc and defg. First, flip the two parts: cbagfed, and then flip the entire string: defgabc.

Enter two strings to remove all characters from the first string.

For example, if you enter "They are students." and "aeiou", the first string after deletion becomes "Thy r stdnts .". The idea of this question can also be completed with dual pointers. First, we have to set a hash table to record which letters appear in the second string. When the hash value is equal to 1, it indicates that it appears in the second string, that is, the string to be removed. If it is equal to 0, it indicates that it does not appear. Then traverse the first string and set two pointers, one p_slow and one p_fast. If the hash value of a word is 1, the word is to be removed from the original string, then p_fast ++. The explanation is a bit unclear. Let's give the code directly.

#include<stdio.h>  #include<stdlib.h>  #include<string.h>    void trim_string(char *string, char *trim_str) {      int hash[256] = {0};      int len_trim = strlen(trim_str);      char *p_slow = string;      char *p_fast = string;      int i;      for(i = 0; i < len_trim; i++) {          hash[trim_str[i]]++;      }      while(*p_fast) {          if(hash[*p_fast] > 0) {              p_fast++;          } else {              *p_slow++ = *p_fast++;          }      }      *p_slow = '\0';  }    void main() {      char string[] = "They are students.";      char trim[] = "aeiou";      trim_string(string, trim);      printf("%s\n", string);  }

Deletes repeated characters in the string within the O (n) time, and does not use Hash.

Bitmap:

#include<stdio.h>  #include<string.h>    void remove_duplicate(char *str) {// assume all characters are little       char *p_slow = str;      char *p_fast = str;      int flag = 0;      int value;      int bits;      while(*p_fast) {          value = 1;          bits = *p_fast - 'a';          value = (value << bits);          if((flag & value) == value) {              p_fast++;          } else {              *p_slow++ = *p_fast++;              flag |= value;          }      }      *p_slow = '\0';  }    void main() {      char str[] = "abcddbcdefghijm";      remove_duplicate(str);      printf("%s\n", str);      getchar();  }

Reverses the order of words in a sentence and ignores punctuation.

Reversing the order of words in a sentence, that is, reversing the order of words in an English sentence and ignoring the processing of punctuation. For example, after I love linux programming. The result is. programming linux love I. You also need to set a double pointer. This situation is similar to that of Question 1, but it is not exactly the same. You need to make some judgments during the reversal process. The following code is provided:

# Include <stdio. h> # include <string. h> void swap_block (char * start, char * end) {char temp; while (start <end) {temp = * start; * start = * end; * end = temp; start ++; end -- ;}} void reverse_sentence (char * str) {char * p_slow = NULL; char * p_fast = NULL; swap_block (str, str + strlen (str) -1); p_slow = str; p_fast = str; while (* p_fast) {if (* p_fast> = 'A' & * p_fast <= 'Z ') | (* p_fast> = 'A' & * p_fa St <= 'Z') {p_fast ++;} else {swap_block (p_slow, p_fast-1); while (! (* P_fast> = 'A' & * p_fast <= 'Z ')&&! (* P_fast> = 'A' & * p_fast <= 'Z') {p_fast ++; // skip unnecessary spaces} p_slow = p_fast ;}}} void main () {char str [] = "I love linux programming. "; reverse_sentence (str); printf (" % s \ n ", str); getchar ();}

I am the dividing line of tiantiao

 

 

Reference: http://blog.csdn.net/zzran/article/details/8456721

Reference: http://blog.csdn.net/zzran/article/details/8108787

 


What are the basic algorithms for data structures?

I. Sorting Algorithm 1. Simple sorting (including Bubble sorting, insertion sorting, and selection sorting) 2. Fast sorting, common 3. Heap sorting, 4. Merge Sorting, the most stable, that is, there is no such difference. 2. The most basic search algorithms include binary search algorithms and the most common search algorithms, the premise is that the sequence has already been ordered, there are deep priority and limited breadth search; and the pruning, A *, hash table and other methods are used to optimize it. Iii. Of course, for basic data structures, stacks, queues, and trees. There are some basic operations, such as stack pop, push, and queue headers, such as queues; and the specific implementation of these data structures, using continuous storage space (array ), or use a linked list. The specific implementation of the operation methods under the two storage methods is different. There are also Tree operations, such as first-order traversal, middle-order traversal, and subsequent traversal. Of course, these are just some basic algorithms for data structures. The basic algorithms should have the following ideas: 1. Backtracking 2. recursion 3. Greedy 4. Dynamic Planning 5. Divide and conquer some data structures and textbooks do not involve basic algorithms, lz can also look for some basic algorithm books. If you are interested, you can do the exercises on oj. Algorithms are hard to learn.

What are the basic algorithms for data structures?

The so-called basic algorithm should refer:
I. Sorting Algorithm
1. Simple sorting (including Bubble sorting, insertion sorting, and selection sorting)
2. Fast sorting, very common
3. Heap sorting,
4. Merge Sorting, which is the most stable, that is, there is no bad situation.
Ii. Search Algorithms
The most basic is the binary search algorithm, the most common search algorithm, provided that the sequence has been ordered
Deep priority and limited breadth search are also available. pruning, A *, hash table, and other methods are used to optimize the search.
Iii. Of course, for basic data structures, stacks, queues, and trees. There are some basic operations
For example, stack pop, push, queue headers, such as queues; and the specific implementation of these data structures, using continuous storage space (arrays), or using linked lists, the specific implementation of the operation methods under the two storage methods is different.
There are also Tree operations, such as first-order traversal, middle-order traversal, and subsequent traversal.
Of course, these are just some basic algorithms for data structures.
The basic algorithms should have the following ideas:
1. Backtracking
2. Recursion
3. Greedy
4. Dynamic Planning
5. Sub-Governance
Some data structure textbooks do not involve basic algorithms. lz can also look for some basic algorithm books. If you are interested, you can do the exercises on oj. Algorithms are hard to learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.