50 lines
1.2 KiB
C++
50 lines
1.2 KiB
C++
|
/**
|
|||
|
* File: linear_search.cpp
|
|||
|
* Created Time: 2022-11-25
|
|||
|
* Author: krahets (krahets@163.com)
|
|||
|
*/
|
|||
|
|
|||
|
#include "../utils/common.hpp"
|
|||
|
|
|||
|
/* <20><><EFBFBD>Բ<EFBFBD><D4B2>ң<EFBFBD><D2A3><EFBFBD><EFBFBD>飩 */
|
|||
|
int linearSearchArray(vector<int> &nums, int target) {
|
|||
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
for (int i = 0; i < nums.size(); i++) {
|
|||
|
// <20>ҵ<EFBFBD>Ŀ<EFBFBD><C4BF>Ԫ<EFBFBD>أ<EFBFBD><D8A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
if (nums[i] == target)
|
|||
|
return i;
|
|||
|
}
|
|||
|
// δ<>ҵ<EFBFBD>Ŀ<EFBFBD><C4BF>Ԫ<EFBFBD>أ<EFBFBD><D8A3><EFBFBD><EFBFBD><EFBFBD> -1
|
|||
|
return -1;
|
|||
|
}
|
|||
|
|
|||
|
/* <20><><EFBFBD>Բ<EFBFBD><D4B2>ң<EFBFBD><D2A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
|
|||
|
ListNode *linearSearchLinkedList(ListNode *head, int target) {
|
|||
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
while (head != nullptr) {
|
|||
|
// <20>ҵ<EFBFBD>Ŀ<EFBFBD><C4BF><EFBFBD>ڵ㣬<DAB5><E3A3AC><EFBFBD><EFBFBD>֮
|
|||
|
if (head->val == target)
|
|||
|
return head;
|
|||
|
head = head->next;
|
|||
|
}
|
|||
|
// δ<>ҵ<EFBFBD>Ŀ<EFBFBD><C4BF><EFBFBD>ڵ㣬<DAB5><E3A3AC><EFBFBD><EFBFBD> nullptr
|
|||
|
return nullptr;
|
|||
|
}
|
|||
|
|
|||
|
/* Driver Code */
|
|||
|
int main() {
|
|||
|
int target = 3;
|
|||
|
|
|||
|
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ִ<EFBFBD><D6B4><EFBFBD><EFBFBD><EFBFBD>Բ<EFBFBD><D4B2><EFBFBD> */
|
|||
|
vector<int> nums = {1, 5, 3, 2, 4, 7, 5, 9, 10, 8};
|
|||
|
int index = linearSearchArray(nums, target);
|
|||
|
cout << "Ŀ<EFBFBD><EFBFBD>Ԫ<EFBFBD><EFBFBD> 3 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> = " << index << endl;
|
|||
|
|
|||
|
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ִ<EFBFBD><D6B4><EFBFBD><EFBFBD><EFBFBD>Բ<EFBFBD><D4B2><EFBFBD> */
|
|||
|
ListNode *head = vecToLinkedList(nums);
|
|||
|
ListNode *node = linearSearchLinkedList(head, target);
|
|||
|
cout << "Ŀ<EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD>ֵ 3 <20>Ķ<EFBFBD>Ӧ<EFBFBD>ڵ<EFBFBD><DAB5><EFBFBD><EFBFBD><EFBFBD>Ϊ " << node << endl;
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|